Categories
JavaScript Answers

How to call addEventListener on a querySelectorAll() with classList with JavaScript?

Spread the love

Sometimes, we want to call addEventListener on a querySelectorAll() with classList with JavaScript.

In this article, we’ll look at how to call addEventListener on a querySelectorAll() with classList with JavaScript.

How to call addEventListener on a querySelectorAll() with classList with JavaScript?

To call addEventListener on a querySelectorAll() with classList with JavaScript, we use forEach to loop through each element.

For instance, we write

const cbox = document.querySelectorAll(".box");
cbox.forEach((box) => {
  box.addEventListener("click", () => box.classList.toggle("red"));
});

to select all elements with class box with querySelectorAll.

Then we call forEach to loop through the node list with a callback.

In it, we call addEventListener to add a click event listener to each element.

And we use a function that calls classList.toggle to toggle the red class as the click listener.

Conclusion

To call addEventListener on a querySelectorAll() with classList with JavaScript, we use forEach to loop through each element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *