简体   繁体   中英

toggle class on click with javascript

I am trying to create a simple on click event using js (no jQuery) If I run the below code it only works for the first item I click.

  var listItem = document.querySelector('li'); listItem.addEventListener('click', function(event) { this.classList.toggle('clicked'); }); 
 .clicked { color:red; } 
 <ul id="mylist"> <li>item 1</li> <li>item 2</li> </ul> 

I looked at an alternative using

  var listItem = document.getElementById('mylist'); listItem.addEventListener('click', function(event) { this.classList.toggle('clicked'); }); 
  .clicked { background-color:red; } 
  <ul id="mylist"> <li>item 1</li> <li>item 2</li> </ul> 
but this just toggles the ul rather than the li I clicked.

How can I target all li in my list so that each time they are clicked their class is toggeled

You should use querySelectorAll instead of querySelector, then loop over all list items:

var listItems = document.querySelectorAll('li');
for(var i = 0; i < listItems.length; i++){
    listItems[i].addEventListener('click', function(event) {
      this.classList.toggle('clicked');
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM