getElementsByTagName Event Listener JavaScript

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.


HTML Code is given below, in this code we have three HTML span tags.

<span>Event Listener</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.

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

     alert('Click Event Added!');
 }, false);


Video Tutorial

Watch video tutorial on How To add Event Listener to elements with getElementsByTagName in 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 JavaScript Change li Text JavaScript Remove id from Element Check If id Exists in JavaScript How To Delete Table Row by id in JavaScript Update Textarea value in JavaScript Change Variable Value in JavaScript Uncheck Radio Button Dynamically JavaScript Check Radio Button Dynamically JavaScript JavaScript Check if Radio Button is Checked or Not Change h1 Tag Text with JavaScript Remove First li from ul JavaScript