Adding a JavaScript Event Handler (with addEventListener) to Multiple Elements Bookmark

There are a variety of use cases for when you might want to add an EventListener with addEventListener to an element to change its native behaviour. Sometimes event handlers need to get attached to single elements, other times adding to multiple elements at once can be neccessary.

Most of the time when I do need to add it to multiple elements, I can’t remember… This post serves as a little reminder for myself (and possibly you), in case I forget again, which is pretty surely going to happen. And that’s ok.

Adding an EventListener to a single element that is listening to the click event often looks like this.

document.querySelector('.button').addEventListener('click', event => {
  // do something on click

Yet sometimes you want to add an EventListener to multiple elements. This can be helpful when you want to execute the same function on different elements, e.g. each with its own parameter, option, etc.

One way to add an Event Listener to multiple elements is by using the convenience of a for…of statement, which creates a loop to iterate over its passed elements.

let buttons = document.querySelectorAll('.button');

for(i of buttons) {
  i.addEventListener('click', function() {
    // do something on click

Another way to add an EventListener to multiple elements is by using a forEach() loop.

With querySelectorAll() we’re selecting all elements with the .button class, then we iterate over all of these elements with forEach() and add the EventListener (for the ‘click’ event) to each of them. The code to do so looks like this:

document.querySelectorAll('.button').forEach(item => {
  item.addEventListener('click', event => {
    // do something on click

For situations where elements do not have the same class name, but require the same EventListener, it’s possible to create an array to select all elements.

[document.querySelector('.button'), document.querySelector('.other-element')].forEach(item => {
  item.addEventListener('click', event => {
    // do something on click

By now and with the above examples, you (and my future self) should have a good idea on the different possibilities of how to use addEventListener on multiple elements. With that, go build something and have a nice day!

Please reach out if you have any comments or further improvements to the above snippets.

Leave a comment

Available formatting commands

Use Markdown commands or their HTML equivalents to add simple formatting to your comment:

Text markup
*italic*, **bold**, ~~strikethrough~~, `code` and <mark>marked text</mark>.
- Unordered item 1
- Unordered list item 2
1. Ordered list item 1
2. Ordered list item 2
> Quoted text
Code blocks
// A simple code block
// Some PHP code
[Link text](
Full URLs are automatically converted into links.

Replied on your own website? Send a Webmention!