I'm trying to make it so that when clicking on a li:
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>
removeClass() and addClass() are not methods of classList. What you're looking for is add() and remove().
const is useful for preventing against accidental variable overwriting. In this situation since you're not reassigning the value of menuLis, I would use const
const 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.remove('selected');
console.log('class removed');
}
// 2. Add Class to Relevant Li
this.classList.add('selected');
console.log('class added');
});
}
<ul id='top-nav'>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
li.classList.remove is correct and for add class use add instead of addClass
you should change your code to:
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.remove('selected');
console.log('class removed');
}
// 2. Add Class to Relevant Li
this.classList.add('selected');
console.log('class added');
});
}
<ul id='top-nav'>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With