Home > Article > Web Front-end > How to Simplify Event Listener Assignment for Multiple Elements?
Simplifying Event Listener Assignment for Multiple Elements
You may encounter a situation where you need to add event listeners to multiple elements. While it's possible to assign listeners individually as shown:
element1.addEventListener("input", function() { // This function does stuff });
or by chaining conditional statements:
element1 && element2.addEventListener("input", function() { // This function does stuff });
these methods can become tedious when dealing with many elements. A more efficient approach is to utilize the forEach() method on an array of the elements:
let elementsArray = document.querySelectorAll("whatever"); elementsArray.forEach(function(elem) { elem.addEventListener("input", function() { // This function does stuff }); });
By iterating through the array, this code assigns the event listener to each element in a single line, simplifying your code and streamlining the event-handling process.
The above is the detailed content of How to Simplify Event Listener Assignment for Multiple Elements?. For more information, please follow other related articles on the PHP Chinese website!