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.

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