Languages
[Edit]
EN

JavaScript - add event listener to multiple elements

0 points
Created by:
Zoya-Gaines
263

In this article, we would like to show you how to add event listener to multiple elements in JavaScript.

Quick solution:

// add onclick event to multiple elements with the same class property

document.querySelectorAll('.element-class').forEach((item) => {
  item.addEventListener('click', (event) => {
    console.log('onclick event occurred.');
  });
});

or

// add onclick event to multiple elements with different class property

[
  ...document.querySelectorAll('.element-class1'),
  ...document.querySelectorAll('.element-class2'),
].forEach((item) => {
  item.addEventListener('click', (event) => {
    console.log('onclick event occurred.');
  });
});

 

Practical examples

1. Add event listener to multiple elements (common class)

In this example, we will add click event listener to multiple elements with the same class property values.

Runnable example:

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
  <body>
    <div class="my-div">Click me! (my-div first)</div>
    <div class="my-div">Click me! (my-div second)</div>
    <script>
    document.querySelectorAll('.my-div').forEach((item) => {
      item.addEventListener('click', (event) => {
        console.log('onclick event occurred.');
      });
    });
    </script>
  </body>
</html>

2. Add event listener to multiple elements (different classes)

In this example, we add click event listener to multiple elements with different class property values in the following way:

  1. we use querySelectorAll to get all the elements from my-div1 and my-div2 classes,
  2. with the spread operator (...) we merge two arrays of elements into one,
  3. using forEach we add an event listener to every item from the merged array.

Runnable example:

// ONLINE-RUNNER:browser;

<!DOCTYPE html>
<html>
  <body>
    <div class="my-div1">Click me! (my-div1)</div>
    <div class="my-div2">Click me! (my-div2)</div>
    <script>
      [
        ...document.querySelectorAll('.my-div1'),
        ...document.querySelectorAll('.my-div2'),
      ].forEach((item) => {
        item.addEventListener('click', (event) => {
          console.log('onclick event occurred.');
        });
      });
    </script>
  </body>
</html>

Note:

Instead of the class you can use any other property to select the elements (e.g. id). However, remember to use a different selector (# instead of .).

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join