-1

I ran into a problem in my work and ran into an error.

error : error image

code :

const open_menu = document.querySelector("#open-menu");
const close_menu = document.querySelector("#close-menu");
const nav_box = document.querySelector(".nav-box");
const eye_slash = document.querySelector(".fa-eye-slash");
const eye = document.querySelector(".fa-eye");

open_menu.addEventListener("click",function (){nav_box.classList.remove("off")});
close_menu.addEventListener("click",function (){nav_box.classList.add("off")});

eye_slash.addEventListener("click",function (){
    document.querySelector("#password").type = "password";
});

const swiper = new Swiper('.swiper', {
    direction: 'horizontal',
    loop: true,
    autoplay: {
        delay: 4000,
    },
    navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
    },
});

I want to know how to solve this problem. Because I have faced this problem a lot.

Parham
  • 5
  • 5

1 Answers1

0

When the element can't be found, document.querySelector will return null. So, you can check to see if the variable is equal to null.

var open_menu = document.querySelector("#open-menu")
…
if (open_menu != null) {
  open_menu.addEventListener("click", …)
} else {
  // the open_menu element doesn't exist
}

Then repeat that for each element you need to use.

Or, if you are using a newer version of JavaScript, you can use optional chaining.

open_menu?.addEventListener("click", …)

The downside of that is that you can't do anything if open_menu is null.

Gavin Morrow
  • 711
  • 1
  • 6
  • 19