Add Event Listener To all Elements of Class JavaScript

In this tutorial we will see how to Add Event Listener To all Elements of same Class in JavaScript. HTML Dom getElementsByClassName() and addEventListener() methods can be used for this purpose.

HTML Code

HTML Code is given below, in this code we have three HTML tags, two tags p tag and h1 tag have same classes, while the third tag h2 has a different class.

<p class="red">Red</p>    
<h1 class="red">Red</h1>
<h2 class="yellow">Yellow</h2>   

JavaScript Code

Take a look at the JavaScript code, the HTML Dom getElementsByClassName() method is used to select all HTML elements with same class.

Then for loop is used to loop through all these selected elements and addEventListener() method is used to add or attach click event listener to them.

alert() method is used to display the message that click event has been added.

You can add any event listener to any HTML element using this code.

<script>
var elem = document.getElementsByClassName('red');

for(var i = 0; i < elem.length; i++) {
 elem[i].addEventListener('click', function(){

     alert('Click Event Added!');
     
 }, false);
}
</script>

Demo

Video Tutorial

Watch video tutorial on How To Add Event Listener To all Elements of same Class in JavaScript.

How to Change Image on Hover with JavaScript How to Disable Button by Class Name in JavaScript How To Change Image Size with JavaScript How to change Image opacity with JavaScript How to Change image src on click with JavaScript How to get the lang attribute value in JavaScript How to Get attribute Value using JavaScript How To Check if Attribute Exists or not with JavaScript How To Count number of links on Page with JavaScript How To Scroll Page to Bottom using JavaScript How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript Change id of Element with JavaScript JavaScript Change li Text Color