event listener to elements with class

Event Listener to Elements with Class

If you want to add an event listener to elements with a certain class, you can do so using JavaScript.

Using document.querySelectorAll()

The easiest way to select all elements with a certain class is to use the document.querySelectorAll() method. This method returns a NodeList of all elements that match the given selector.

const elements = document.querySelectorAll('.my-class');
elements.forEach(element => {
  // Add event listener to each element
  element.addEventListener('click', () => {
    // Do something when element is clicked
  });
});

In this example, we select all elements with the class "my-class" and add a click event listener to each one using a forEach loop.

Using addEventListener() with event delegation

If you have a large number of elements with the same class and adding an event listener to each one would be inefficient, you can use event delegation instead. Event delegation means adding an event listener to a parent element and checking if the event target matches the desired selector.

const parentElement = document.querySelector('.parent-element');
parentElement.addEventListener('click', event => {
  if (event.target.matches('.my-class')) {
    // Do something when an element with class "my-class" is clicked
  }
});

In this example, we add a click event listener to the parent element with class "parent-element" and check if the event target matches the ".my-class" selector. If it does, we can handle the event accordingly.

Both of these methods are effective ways to add event listeners to elements with a certain class, depending on your specific use case.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe