document.querySelectorAll()
returns a node list (collection of elements) and a collection of elements doesn't have a classList
, a single element does. Instead make the code
this.classList.add("active");
because this
will be bound to the object that triggered the event callback in the first place, which is the element that you want the style added to.
But, better yet, instead of looping over all the buttons and attaching the same event listener to each of them, use event delegation and just add a single event listener to the parent of all the buttons. Because events bubble, the event will reach the parent and is handled there. When it is handled, using event.target
you can access the object that initially triggered the event and operate on it that way.
Here's an example:
// Add the event listener to the parent
document.querySelector(".buttons").addEventListener("click", function(event){
// Whichever button was clicked will be the: event.target
event.target.classList.toggle("active");
});
.active { background-color:#ff0; }
<div class="buttons">
<button type="button">One</button>
<button type="button">Two</button>
<button type="button">Three</button>
</div>