toggle class on click with javascript

2019-09-03 21:20发布

问题:

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

回答1:

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');
    });
}