How to add an EventListener to multiple elements in JavaScript

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:

  1. Select all the elements we want to listen to.

  2. Loop through the selected elements.

  3. 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:

const buttons = document.querySelectorAll('.sign-in-btn');

This will select all buttons with the class sign-in-btn.

Step 2: Looping through elements

Once we’ve selected the elements, we need to loop over them to apply the event listener to each one. We can use a simple forEach() loop to iterate over the NodeList.

buttons.forEach(button => {
// Add click event listener to each button
});

Step 3: Adding the EventListener

Within the loop, we can use addEventListener() to attach the desired event to each element.

buttons.forEach(button => {
button.addEventListener('click', (event)=> {
// ... Event handled
});
});

Let’s see this in action by attaching a click event to two sign-in buttons.

Example: Adding click event to multiple sign-in buttons

Let’s say a page has two sign-in buttons, and we need to perform the same operation by clicking both buttons.

  • HTML
Adding click event to multiple buttons in JavaScript

In the above code:

  • Lines 6–7: We create two button elements in HTML, both with the class sign-in-btn.

  • Line 12: We use querySelectorAll('.sign-in-btn') to select all sign-in buttons on the page.

  • Line 15: We loop over the buttons NodeList using the forEach() method.

  • Lines 17–20: Inside the loop, we attach a click event listener to each button that triggers an alert saying “Sign-in button clicked!” when any button is clicked.

Using multiple event listeners on other elements

This method works for any set of elements. For example, we can easily add a hover effect to all list items:

  • HTML
Using multiple event listeners on multiple elements in JavaScript

In the above code:

  • Lines 7–13: We create an unordered list <ul> containing list items <li> for each working day (Monday to Friday).

  • Line 17: We use document.querySelectorAll('li') to select all <li> elements in the document, storing the result in the listItems variable as a NodeList.

  • Lines 19–27: We loop through each item in listItems using the forEach() method. For each item:

    • Lines 20–22: We add an event listener for the mouseover event, which triggers when the mouse pointer hovers over the list item. Inside this event handler, we set the backgroundColor of the item to yellow, giving a visual indication of hover.

    • Lines 24–26: We add an event listener for the mouseout event, which triggers when the mouse pointer leaves the list item. Inside this event handler, we revert the backgroundColor of the item back to white.

Using event delegation for better performance

When we need to add an event listener to a large number of elements, looping through all of them may affect performance. In such cases, we can use event delegation, which leverages the concept of event bubbling.

Instead of attaching the listener to every element, we attach a single event listener to a parent element. This method catches events that bubble up from the child elements, reducing the number of listeners attached.

  • HTML
Using event delegation in JavaScript

In the above code:

  • Line 16: We select the <ul> element from the HTML document using document.querySelector().

  • Lines 18–22: We add an event listener to the daysList that listens for the mouseover event. Inside the event listener, we check if the event’s target element is a list item (<li>) by using the condition event.target.tagName === 'LI'. When the condition is true, we change the background color of the target list item to yellow by setting the backgroundColor style property.

  • Lines 24–28: We add another event listener to the daysList that listens for the mouseout event and reset the background color of the target list item to white.

Benefits of using event delegation over looping

Here are some benefits of using event delegation in JavaScript:

  • Improved performance: Event delegation attaches a single event listener to a parent element (like <ul>) that can handle events for all of its child elements (like <li> items). This reduces memory usage, as only one event listener is created. Looping would require attaching a separate event listener to each child element, increasing memory usage and slowing down performance.

  • Less maintenance: With delegation, new elements added dynamically to the parent (e.g., new <li> items) will automatically be covered by the single-parent event listener. There’s no need to manually attach new listeners to these elements. When using a for loop, each new element would require the manual attachment of a new event listener.

  • Cleaner code: In event delegation, we only write the event listener once on the parent element, keeping the code concise and easy to understand. Using a loop means writing more code, as we need to iterate over all elements and attach individual listeners to each one.

  • Better for dynamic content: Event delegation is perfect for dynamically generated content. If elements are added or removed from the DOM, the single event listener will still capture events on any new child elements. In looping, we need to re-run the loop each time the DOM changes to add event listeners to new elements, making it less flexible.

  • Propagation control: Event delegation takes advantage of event propagation (bubbling) where events automatically bubble up from child elements to the parent. This allows a parent to manage events from all its children in a controlled manner. In looping, each event listener attached to individual elements is isolated, so managing events collectively would require more complex code.

In summary, event delegation is more efficient, scalable, and easier to maintain than using a for loop to attach individual event listeners. It’s particularly beneficial when dealing with dynamic content or a large number of elements.

You can explore our JavaScript Catalog to learn everything from basics to advanced concepts!

Knowledge test

Let’s attempt a short quiz to assess your understanding.

Q

Which method can be used to select multiple elements in JavaScript?

A)

document.getElementById()

B)

document.querySelectorAll()

C)

document.getElementByClassName()

D)

document.querySelector()

Conclusion

Adding event listeners to multiple elements is essential for building dynamic, interactive web applications. While looping through elements and attaching individual listeners works, event delegation is a more efficient approach, especially for large sets of elements or dynamic content. By attaching a single event listener to a parent element, event delegation simplifies the code, enhances performance, and ensures scalability.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to add the same event listener to multiple elements in JavaScript

To add the same event listener to multiple elements in JavaScript, you can follow these steps:

  1. Select the elements: Use document.querySelectorAll() to select multiple elements.
  2. Loop through the elements: Use a loop (e.g., forEach()) to iterate through the NodeList.
  3. Attach the event listener: Use addEventListener() to attach the desired event to each element.
const buttons = document.querySelectorAll('.my-button');
buttons.forEach(button => {
    button.addEventListener('click', () => {
        alert('Button clicked!');
    });
});

How to add multiple event listeners in JavaScript

To add multiple event listeners to a single element, you can call addEventListener() multiple times with different event types and handlers.

const button = document.querySelector('.my-button');
button.addEventListener('click', () => {
    console.log('Button clicked!');
});
button.addEventListener('mouseover', () => {
    console.log('Mouse over the button!');
});

How to add an event listener to an array of elements

You can add an event listener to an array of elements using forEach() or a regular loop. If you’re working with a NodeList returned by querySelectorAll(), you can directly use forEach().

const items = document.querySelectorAll('li');
items.forEach(item => {
    item.addEventListener('mouseover', () => {
        item.style.backgroundColor = 'yellow'; // Change color on hover
    });
    item.addEventListener('mouseout', () => {
        item.style.backgroundColor = 'white'; // Reset color when not hovered
    });
});

Free Resources