Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Event Listener to Collection of HTML Elements

Tags:

javascript

I know that getElementsByTagName and getElementsByClassName need an index identifier in order for the objects to be bound to an event listener.

So the question is, how do I add an event listener to a collection of HTML elements found using getElementsByTagName or getElementsByClassName?

<input class="inputs" type="submit" value="Hello" />
<input class="inputs" type="submit" value="World" />

var inputElem = document.getElementsByTagName('input');
inputElem.addEventListener('click', function(){
    alert(this.value);
}, false);

I know how to do this in jQuery, but I want to know how to do it with pure JS.

like image 204
Josan Iracheta Avatar asked Jan 08 '15 06:01

Josan Iracheta


3 Answers

Adding eventlistener to each of them is not advisable. May be this can help:

http://jsfiddle.net/b8gotLL6/

document.getElementById('parent').addEventListener('click', function(e){
alert(e.target.value);
})

And if you only want to do using getElementsByTagName or getElementsByClassName, then i guess you need to iterate for the array returned.

like image 121
Rakesh_Kumar Avatar answered Oct 13 '22 07:10

Rakesh_Kumar


you can try like this:first get all the element of the particular type the loop through it.

var elems = document.getElementsByClassName('inputs');
for(var i = 0; i < elems.length; i++) {

    elems[i].addEventListener('click', function(){
        alert(this.value);
    }, false);
}
<input class="inputs" type="submit" value="Hello" />
<input class="inputs" type="submit" value="World" />
like image 45
Suchit kumar Avatar answered Oct 13 '22 08:10

Suchit kumar


It's pretty simple like @Rutwick Gangurde said. Once you get the elements you just need to loop through and attach the event.

var inputElem = document.getElementsByTagName('input');

for(var i = 0; i < inputElem.length; i++) {

    inputElem[i].addEventListener('click', function(){
        alert(this.value);
    }, false);
}

Here it is in a fiddle: http://jsfiddle.net/wm7p0a77/

like image 43
atxpunkrock Avatar answered Oct 13 '22 07:10

atxpunkrock