How to Add Event Listener to Multiple Elements with Same Class using JavaScript?

If you have multiple elements on a page with a same class and you want to add an event listener to each of them, you have to first select all the elements using any DOM selector method such as getElementsByClassName() or querySelectorAll().

The selector methods like getElementsByClassName() and querySelectorAll() returns an array containing all the matching elements.

Therefore, you have to loop through the array and then add the event listener to each element of it using the addEventListener() method of the DOM.

Let’s say we have multiple paragraphs in our HTML which have a common class 'para':

<div>
    <p class="para">This is first paragraph</p>
    <p class="para">This is second paragraph</p>
    <p class="para">This is third paragraph</p>
</div>

Now, we want to attach a click event listener to each paragraph that has the class="para" so that we could detect whenever someone clicks on it.

Here is the implementation of all the above steps with a live example:

Example:

// Fetch all elements having class para
let elements = document.getElementsByClassName('para');

// Loop through the elements array 
// and attach a click event listener to each one 
for(let i=0;i<elements.length;i++){
    elements[i].addEventListener('click', function(event){
        // Alert on click
        alert('You have clicked: '+ event.target.innerText); 
    });
}

You can also do it by selecting all the paragraphs using the querySelectorAll() method of the DOM.

The rest of the code will remain the same:

// Fetch all elements having class para
let elements = document.querySelectorAll('.para');

// Loop through the elements array 
// and attach a click event listener to each one 
for(let i=0;i<elements.length;i++){
    elements[i].addEventListener('click', function(event){
        // Alert on click
        alert('You have clicked: '+ event.target.innerText); 
    });
}

Thanks for reading.


Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts