Skip to content

How to add an event listener to multiple elements in JavaScript

New Course Coming Soon:

Get Really Good at Git

Say you want to add an event listener to multiple elements in JavaScript. How can you do so?

In JavaScript you add an event listener to a single element using this syntax:

document.querySelector('.my-element').addEventListener('click', event => {
  //handle click
})

But how can you attach the same event to multiple elements?

In other words, how to call addEventListener() on multiple elements at the same time?

You can do this in 2 ways. One is using a loop, the other is using event bubbling.

Using a loop

The loop is the simplest one conceptually.

You can call querySelectorAll() on all elements with a specific class, then use forEach() to iterate on them:

document.querySelectorAll('.some-class').forEach(item => {
  item.addEventListener('click', event => {
    //handle click
  })
})

If you don’t have a common class for your elements you can build an array on the fly:

[document.querySelector('.a-class'), document.querySelector('.another-class')].forEach(item => {
  item.addEventListener('click', event => {
    //handle click
  })
})

Using event bubbling

Another option is to rely on event bubbling and attach the event listener on the body element.

The event is always managed by the most specific element, so you can immediately check if that’s one of the elements that should handle the event:

const element1 = document.querySelector('.a-class')
const element2 = document.querySelector('.another-class')

body.addEventListener('click', event => {
  if (event.target !== element1 && event.target !== element2) {
    return
  }
  //handle click
}
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: