0

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 Answer 1

6

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');
    });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.