Skip to content Skip to sidebar Skip to footer

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. I looked at an alternative using but this jus

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

Post a Comment for "Toggle Class On Click With Javascript"