Skip to content
the poor coder

event listener to elements with class

Poor Man
Published
Reading time
1 min read
On this page

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.

Text
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.

Text
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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC