I know that getElementsByTagName
and getElementsByClassName
need an index identifier in order for the objects to be bound to an event listener.
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.
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/
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" />
var i=0, inputElem = document.getElementsByTagName('input'), len = inputElem.length;
while(i < len){
inputElem[i].addEventListener('click', function(){
alert(this.value);
}, false);
i++;
}
First, use getElementsByClassName, instead of getElementsByTagName. Then Loop through them, adding the event listener like this:
var inputElem = document.getElementsByClassName('inputs');
var i;
for (i = 0; i < inputElem .length; i++) {
inputElem [i].addEventListener('click', (function(i) {
return function() {
alert(this.value);
};
})(i), false);
}
Here it is on jsfiddle
Try querySelectorAll
method.
var inputElem = document.querySelectorAll('input');
Which returns a NodeList
and you can loop through the array to add the event listeners.