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.
Table of Contents
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.