html – Add and remove classes when click on multiple divs using javascript

0
95
html - Animation after toggling doesn't apply the second style


I am actually trying to add class (Selected) to the li when clicked and remove Class from neighbour li.

Issue is it doesn’t work when there is 2 ul, the below code only work on the 1st ul or when i click on the li of the second li, first li active gets removed

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');
    }
    
    // 2. Add Class to Relevant Li
    this.classList.add('selected');
  });
  
}
.selected{color:red}
<ul id='top-nav'>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>

<ul id='top-nav'>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>

Thank you for the help



Source link

Leave a reply

Please enter your comment!
Please enter your name here