How to Add an Event Listener to Multiple Elements in JavaScript
If you want to add an event listener to multiple elements in JavaScript, there are a couple of approaches you can take. In this article, we will explore two methods: using a loop and leveraging event bubbling.
Method 1: Using a Loop
The first method involves using a loop to iterate over the elements and attach the event listener individually. Here’s an example:
1 | document.querySelectorAll('.some-class').forEach(item => { |
In the above code, querySelectorAll()
is used to select all elements with a specific class. Then, forEach()
is used to iterate over each element and attach the event listener to it.
If your elements don’t share a common class, you can create an array of the elements on the fly and then iterate over it:
1 | [document.querySelector('.a-class'), document.querySelector('.another-class')].forEach(item => { |
By using a loop, you can easily add the event listener to multiple elements without duplication.
Method 2: Using Event Bubbling
The second method involves utilizing event bubbling. Event bubbling is a mechanism in JavaScript where an event that is triggered on a particular element will also trigger on all of its parent elements. By attaching the event listener to a parent element higher up in the DOM hierarchy, you can handle events on multiple elements simultaneously.
Here’s an example of using event bubbling:
1 | const element1 = document.querySelector('.a-class'); |
In the code above, the event listener is attached to the body
element, which is a common parent element of element1
and element2
. When a click event happens, the event will bubble up to the body
element. Inside the event handler, you can check if the target of the event matches one of the desired elements before proceeding with the desired functionality.
Using event bubbling can be particularly useful when you have a large number of elements or when new elements may be added dynamically to the DOM.
In conclusion, adding an event listener to multiple elements in JavaScript is achievable either through a loop or by leveraging event bubbling. Choose the method that best fits your specific needs and coding style.
tags: [“JavaScript”, “event listener”, “event bubbling”, “loop”, “querySelectorAll”]