Key takeaways:
Use document.querySelectorAll()
to grab multiple elements of the same type, such as buttons, images, or list items.
Loop over the selected elements using forEach()
and attach event listeners using addEventListener()
.
For better performance and easier maintenance, use event delegation by attaching a single event listener to a parent element to handle child elements’ events.
Event delegation works by utilizing event bubbling, which propagates events from child elements to parent elements.
In interactive web applications, we often need to respond to user actions such as clicks, key presses, or mouse movements. While adding an event listener to a single element is straightforward, real-world projects often require attaching event listeners to multiple elements of the same type, such as buttons, images, or list items. This can be done efficiently using JavaScript’s addEventListener()
method, along with techniques for selecting multiple elements.
In this Answer, we’ll learn how to add event listeners to multiple elements and manage them effectively.
Adding EventListener
to multiple elements
To add an event listener to multiple elements, we generally follow these steps:
Select all the elements we want to listen to.
Loop through the selected elements.
Attach the event listener to each element within the loop.
Let’s walk through each of these steps in detail.
Step 1: Selecting multiple elements
In JavaScript, we can use document.querySelectorAll()
to select multiple elements at once. This method returns a NodeList
, which is a collection of DOM elements matching a given CSS selector.
For example, to select all buttons on a page, we can use: