Event Listeners for Multiple Elements in JavaScript

Here’s how to add an event listener for multiple DOM elements in JavaScript.

Published Categorized as JavaScript, Web Dev

Suppose you want to create an event listener for more than one DOM elements in your HTML document with JavaScript.

What’s the best way to achieve this?

To register an event listener for multiple elements, create a forEach loop using the querySelectorAll() method or implement a generic click listener with conditional logic.

This tutorial will show you exactly how to do this, both ways.

With a Loop

In JavaScript, you can target multiple DOM elements with a CSS selector using the Document.querySelectorAll() method.

The Document.querySelectorAll() method returns a static NodeList with all the DOM elements matching the CSS selection criteria that you’ve passed onto it as an argument.

Once you’ve obtained the NodeList, you can iterate on it using the Array.forEach() method. For example, let’s add an event listener to all link clicks using a CSS selector that targets <a> elements:

// Create event listener for all link clicks
document.querySelectorAll('a').forEach(occurence => {
  occurence.addEventListener('click', (e) => {
    console.log('A link was clicked');
  });
});

The degree to which you can target groups of DOM elements with this method is limited only by your imagination, ingenuity, and proficiency in CSS selectors.

With Conditional Logic

Another way to solve this challenge is using a generic event listener that fires on all occurences of the event, and then narrowing down the execution of your code with conditional logic.

You can register a generic event listener for the event type you want to listen to. Then, you can implement conditional checks based on the desired attributes of your target DOM element.

You do this by passing on e, short for event, as an argument to your function. This, in turn, allows you to access the read-only attributes of the DOM element that the event listener was attached to using the Event.target() interface within the Event Web API.

This conditional logic can be an if, elseif, and/or else statement:

// Register event listener for all click events
document.addEventListener('click', (e) => {
  // Store tagName in a variable
  let criterion = e.target.tagName;
  // Implement conditional logic based on the value of the variable
  if (criterion = "A") {
    console.log('A link was clicked');
  }
});

Or, when you need to search for matches against a long set of criteria, the conditional logic can be implemented with the faster and more computationally efficient switch statement for the job:

// Register event listener for all click events
document.addEventListener('click', (e) => {
  // Store tagName in a variable
  let criterion = e.target.tagName;
  // Implement conditional logic based on the value of the variable
  switch(attribute) {
    // Clicks on <a>
    case 'A':
      console.log('A link was clicked');
      break;
    // Clicks on <button>
    case 'BUTTON':
      console.log('A button was clicked');
      break;
    // Clicks on all other DOM elements
    default:
      console.log('A DOM element was clicked');
  }
});

When to Use Each

If you want to target one group of elements with a known className or id, you may be better off going for the querySelector() method and iterating on it with a forEach loop.

If you want to target multiple click events and/or multiple groups of elements, consider adding a generic click listener and implementing conditional checks based on the event types of element attributes to drill down for.

In Conclusion

Thank you for reading this far, and I hope this tutorial helped you.

Whether you choose to loop over a NodeList of DOM elements or go for a generic event listener and implement conditional logic, both solutions should do the job.

If you have questions on any of the code above or you want to share solutions of your own with the rest of this post’s readers, be sure to leave a reply below.

Leave a comment

Your email address will not be published.