0

I'm applying eventlistener from a loop to a dropdown menu, but only the last item has its class toggled no matter which item is being clicked on.

$(document).ready(function(){
            var item = document.querySelectorAll('#dropdown .hasSubMenu');
            var len = item.length;

            for (var i = 0; i < len; i++) {
                var items = item[i];
                var menuItem = items.querySelector('.filter');

                menuItem.addEventListener('click', function() {
                    items.classList.toggle('open');
                });
            }
        });

The class 'open' is being added only to the last item from the loop. What am I doing wrong?

esQmo_
  • 1,464
  • 3
  • 18
  • 43
  • 1
    Changing `var items = item[i];` to `let items = item[i];` should do the trick. (Though I'd use `let` for all variables.) – Ivar Jul 20 '21 at 11:53
  • Thank for the advice. I'm new to this complicated Javascript universe. Lots of things to learn and hard to keep the pace – esQmo_ Jul 20 '21 at 11:56
  • *I'm new to this* - you'll find things easier if you use the correct plurals/singular for your variable names. item*s* is plural so should be the for the collection `let items = document.querySelectorAll('#dropdown .hasSubMenu')` then you have `items.length` and `let item = items[i]` which can help you be sure you're using the correct variable. – freedomn-m Jul 20 '21 at 12:49
  • @freedomn-m, sure, you're right. though in my mind I was like item at "i" – esQmo_ Jul 20 '21 at 21:15

1 Answers1

0

The answers from here helped me correct my mistake. I didn't know there was differences between let, var, etc. So among all the excellent solutions, I choosed changing all my vars from var x to let x. This is how I fixed my issue.

esQmo_
  • 1,464
  • 3
  • 18
  • 43