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"
2
Answers
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.
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.
docs: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName