How to add event listeners to multiple elements in JavaScript

Suppose you want to add event listeners to multiple elements in JavaScript. How can you do this?

In JavaScript, you can add aEvent listenerUse the following syntax to convert it to a single element:

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

But how to attach the same event to multiple elements?

In other words, how to calladdEventListener()Use multiple elements at the same time?

You can do this in 2 ways. One is in useRing, The other is usingEvent bubbling.

Use loop

Conceptually, loop is the simplest loop.

You can callquerySelectorAll()On all elements with a specific class, then useforEach()Iterate on them:

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

If your element does not have a common class, you can build an array dynamically:

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

Use event bubbling

Another option is to rely onEvent bubblingAnd attach the event listener tobodyelement.

The event is always managed by the most specific element, so you can immediately check whether that element 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 }

Download mine for freeJavaScript beginner's manual


More js tutorials: