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.

Password Show Hide with Eye Icon using JavaScript Change Background Color using Dropdown menu with JavaScript Get Select Tag value onchange in JavaScript Check If Class Exists JavaScript Add Event Listener To all Elements of Class JavaScript getElementsByTagName Event Listener JavaScript Change type attribute of Input Element With JavaScript Password Hide and Show with Toggle Emoji Button using JavaScript Hide and Show Navbar On Scroll With JavaScript Empty an Array in JavaScript Get Last Element Of Array Without Removing It Remove Last Element From Array JavaScript Remove First Element From Array in JavaScript Tic Tac Toe Game in JavaScript Remove Class from HTML Tag OnClick JavaScript JavaScript Select li Tag By Index Display JavaScript Variable In HTML Insert HTML Code anywhere With JavaScript JavaScript Date Difference in Days JavaScript Hide Button After Click Simple Click and Hold Effect Using JavaScript Remove Class From All Elements in JavaScript JavaScript Select All HTML Elements Whose ID Start With Same String