Home >Web Front-end >JS Tutorial >How to Add Event Listeners to Multiple Elements in One Line of JavaScript?
Adding Event Listeners to Multiple Elements in One Line
When working with multiple HTML elements, it can be cumbersome to add event listeners to each one individually. Fortunately, there's a more efficient way to achieve this using JavaScript.
Consider the following code snippet:
<p>Example 1:</p> <pre class="brush:php;toolbar:false">element1.addEventListener("input", function() { // this function does stuff });
Example 2:
element1 &&& element2.addEventListener("input", function() { // this function does stuff });
While Example 1 adds an event listener to a single element, Example 2 attempts to add an event listener to multiple elements. However, the syntax for Example 2 is incorrect.
The solution lies in using JavaScript's forEach() method. Suppose you have an array containing the elements you wish to add event listeners to. In that case, you can use the following code:
let elementsArray = document.querySelectorAll("whatever"); elementsArray.forEach(function(elem) { elem.addEventListener("input", function() { // This function does stuff }); });
In this code, querySelectorAll("whatever") returns an array of elements that match the specified selector. The forEach() method then iterates over each element in the array and adds the desired event listener.
This method provides a concise and efficient way to add event listeners to multiple elements simultaneously. By utilizing arrays and the forEach() method, you can reduce code redundancy and improve efficiency in your JavaScript projects.
The above is the detailed content of How to Add Event Listeners to Multiple Elements in One Line of JavaScript?. For more information, please follow other related articles on the PHP Chinese website!