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.
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.
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" />
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With