Categories
JavaScript Answers

How to addEventListener to multiple elements in a single line with JavaScript?

Spread the love

Sometimes, we want to addEventListener to multiple elements in a single line with JavaScript.

In this article, we’ll look at how to addEventListener to multiple elements in a single line with JavaScript.

How to addEventListener to multiple elements in a single line with JavaScript?

To addEventListener to multiple elements in a single line with JavaScript, we can loop through each element and call addEventListener on them.

For instance, we write

const elementsArray = [...document.querySelectorAll("input")];

elementsArray.forEach((elem) => {
  elem.addEventListener("input", () => {
    // ...
  });
});

to call querySelectorAll to select all input elements.

Then we use the spread operator to convert the returned node list to an array.

Next, we call elementsArray.forEach with a callback that calls elem.addEventListener to add an input event listener to each element elem.

Conclusion

To addEventListener to multiple elements in a single line with JavaScript, we can loop through each element and call addEventListener on them.

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 *