Coding Triumph

Helpful code snippets & tutorials

How to listen to a single event with multiple elements in JavaScript

Usually, in JavaScript, we listen to a single event from a single element like this:

const button = document.querySelector('button');

button.addEventListener('click', event => {
  // do something...

But what if you need to listen to the same event from multiple elements. Well, we can solve this problem with a simple forEach loop:

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

buttons.forEach(btn => {
  btn.addEventListener('click', event => {
    // do something...
If you like this post, please share
Notify of
Inline Feedbacks
View all comments