How to add an event listener to multiple items in JavaScript

To add an event listener to multiple elements in JavaScript we need to do a few steps:

  1. Get the elements we wish to attach the event listener
  2. Iterate over the elements and add the event listener

Get the elements

The preferred approach to getting an element from the DOM is to use querySelectorAll. This will search the DOM for all button elements:

const buttons = document.querySelectorAll('button')

You can select your own custom classes:

const buttons = document.querySelectorAll('.my-buttons')

and you can even select multiple classes at once:

const buttons = document.querySelectorAll('.my-buttons, .my-other-buttons')

This returns a NodeList (which in this case is assigned to the button variable), which we can loop over. We can use the forEach() higher order function to do this:

// get the buttons from the DOM
const buttons = document.querySelectorAll('button')

// loop over the buttons that were returned from the querySelector
buttons.forEach(button => {

    // some logic here

})

Loop over the elements & add the event listener

As we are looping over each button, we want to attach an event listener to it. We do this within our loop so the code now looks like this:

// get the buttons from the DOM
const buttons = document.querySelectorAll('button')

// loop over the buttons that were returned from the querySelector
buttons.forEach(button => {

    // foreach button we attach a `click` event
    button.addEventListener('click', () => { 
        
        // some logic that runs when this button is "clicked" goes here

    })
})

This example adds a click event listener, but you can add whatever event you want. Check out this CodePen for a running example: