-2

I am trying to make a responsive mobile nav that will close out when a menu item is clicked, but I keep getting an error on this even though I have other scripts in the js file formatted the same way. Can you tell me why I would be getting this error?

Error message: "Uncaught TypeError: navLink.addEventListener is not a function"

JS:

{
    let navLink = document.getElementsByClassName("menu-item");
    //let navLink = document.querySelector(".menu-item a");
    
    navLink.addEventListener("click", () => {
        if (document.querySelector(".nav-header").className === "nav-header responsive") {
            document.querySelector(".nav-header").classList.remove(" responsive");
        }
        else {
            return;
        }
    });
}

If I change the variable rules or anything I also receive an error of xxx is null, so maybe it stems from there?

let navLink = document.querySelector(".menu-item a");

Error message: "Uncaught TypeError: navLink is null"

CF Walker
  • 11
  • 3

2 Answers2

0

document.getElementsByClassName returns an array of elements. So may be you want to target a specific index of them: var navLink[0].addEventListener(.... ) should get you what you want.

SimoPisa
  • 46
  • 1
0

getElementsByClassName() returns an array of elements, because multiple elements on the page can have the same class name.

Assuming you have multiple of these elements on the page, you could use a for loop to add an event listener to each element.

let navLink = document.getElementsByClassName("menu-item");

for(let element of navLink) {
  element.addEventListener("click", () => {
    // code here
  })
}

docs: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName

zmehall
  • 557
  • 3
  • 13