Home > Article > Web Front-end > How to Attach Event Listeners to Multiple Elements in JavaScript Efficiently?
Question:
Is there an efficient way to attach event listeners to multiple elements simultaneously, avoiding the need for separate event handling for each element?
Example:
Traditionally, event listeners are added individually:
element1.addEventListener("input", function() { // this function does stuff }); element2.addEventListener("input", function() { // this function does stuff });
Answer:
In JavaScript, you can utilize the forEach() method on an array of elements to create event listeners for each element in a single line of code.
Solution:
To achieve this, create an array that contains your elements:
let elementsArray = document.querySelectorAll("whatever");
Then, use the forEach() method to iterate through the array and add an event listener to each element:
elementsArray.forEach(function(elem) { elem.addEventListener("input", function() { // This function does stuff }); });
This approach provides a concise and efficient way to add event listeners to multiple elements, streamlining your event handling code.
The above is the detailed content of How to Attach Event Listeners to Multiple Elements in JavaScript Efficiently?. For more information, please follow other related articles on the PHP Chinese website!