I'm trying to make it so that when clicking on a li:
- The li clicked on gets the class 'selected'
- The neighbouring li siblings have the class 'selected' removed
The aim is, whenever clicking on a li, only that li gets a class of 'selected'.
I wrote a simple for of loop and tried adding an event listener to each li, but nothing happens when clicking on any li. Why does this happen, and how can it be fixed?
Also, out of curiosity, would using the const
keyword be more applicable than var
in this case?
Thanks for any help here - the code demos can be found below:
Codepen Demo URL: https://codepen.io/anon/pen/MMgWZY
var menuLis = document.querySelectorAll("#top-nav > li");
for (let li of menuLis) {
li.addEventListener("click", function(){
// 1. Remove Class from All Lis
for (let li of menuLis) {
li.classList.removeClass('selected');
console.log('class removed');
}
// 2. Add Class to Relevant Li
this.classList.addClass('selected');
console.log('class added');
});
}
<ul id='top-nav'>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>