-1

I'm new to javascript and I keep getting an error on one of my function.

this is the code:

const menu_item = document.querySelector('.header .nav-bar .nav-list ul li a');

menu_item.forEach((item) => {
    item.addEventListener('click', () => {
        hamburger.classList.toggle('active');
        mobile_menu.classList.toggle('active');
    });
});

This is the error it keeps throwing: Uncaught TypeError: menu_item.forEach is not a function

Any help would be appreciated Thankss^^!!

2
  • 1
    use querySelectorAll Commented Jul 13, 2020 at 16:05
  • 'tis not an array, you're calling a singular element :) Commented Jul 13, 2020 at 16:11

1 Answer 1

4

Whenever you see ".forEach" is not a function, it means the object on which you're trying to use the method is not an array!

Why? Because ".querySelector" returns a single value, the first value that matches the selector.

You should use ".querySelectorAll" if you want to have a list!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.