Home > Enterprise >  Uncaught TypeError: navItem.forEach is not a function
Uncaught TypeError: navItem.forEach is not a function

Time:09-02

While creating menu in JS and using .forEach console shows: Uncaught TypeError: navItem.forEach is not a function

I'm rather beginner in JS with error like this solving, can anyone help or show how to fix this code? Thanks!

const navItem = document.querySelector(".nav_item");

function activeLink() {
    navItem.forEach((item) =>
    item.classList.remove('active'));
    this.classList.add('active');
}

navItem.forEach((item) =>
item.addEventListener('click',activeLink));

CodePudding user response:

the problem here is that you are using querySelector that returns only the first element. Instead you should use querySelectorAll

const navItem = document.querySelectorAll(".nav_item");

function activeLink() {
    navItem.forEach((item) =>
    item.classList.remove('active'));
    this.classList.add('active');
}

navItem.forEach((item) =>
item.addEventListener('click',activeLink));

CodePudding user response:

You need to use "querySelectorAll", otherwise the forEach loop won't work I think!

  • Related