In this tutorial we will see How To add Event Listener to elements with getElementsByTagName in JavaScript. getElementsByTagName is used to select HTML elements and addEventListener is used to add click event to these elements.
Table of Contents
HTML Code
HTML Code is given below, in this code we have three HTML span tags.
<span>getElementsByTagName</span>
<br>
<span>Event Listener</span>
<br>
<span>JavaScript</span>
JavaScript Code
Take a look at the JavaScript code, the HTML Dom getElementsByTagName method is used to select all span tags.
for loop is used to loop through all these span tags and then addEventListener method is used to add click event listener to them.
<script>
var elem = document.getElementsByTagName('span');
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 elements with getElementsByTagName in JavaScript.