Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle the class of unordered list items using simple Javascript

I am working on a project that requires me to toggle the class of li element every time I click on it.

I have the following code:

var list = document.getElementById('nav').children[0];
for (var i = 0; i < list.children.length; i++) {
  var el = list.children[i];
  el.addEventListener("click", function() {

    el.classList.toggle("myClass");
  });
}
<div id='nav'>
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
  </ul>
</div>

But this code adds the class only to the last li element no matter which li I click on, I have taken reference from Use JavaScript to change the class of an <li> and tried to tailor the same to my needs, but there is something wrong here. Any help will be really appreciated.

like image 950
CodeHumor Avatar asked Oct 29 '25 07:10

CodeHumor


2 Answers

You shouldn't attach the click event inside the loop, create a function out of the loop and call it when you attach the click event like :

var list_items = document.querySelectorAll('#nav>ul>li');

for (var i = 0; i < list_items.length; i++) {
  list_items[i].addEventListener("click", toggle);
}

function toggle() {
  this.classList.toggle("myClass");
}
.myClass {
  color: green;
}
<div id='nav'>
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
  </ul>
</div>
like image 132
Zakaria Acharki Avatar answered Oct 31 '25 13:10

Zakaria Acharki


Change el.classList.toggle("myClass"); to this.classList.toggle("myClass"); and it will work, as it refers to the current element

like image 44
Jimmy Hedström Avatar answered Oct 31 '25 12:10

Jimmy Hedström



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!