Add event listener to collection of HTML elements
I know that the index ID is getElementsByTagName
also getElementsByClassName
needed for the objects to bind to the event listener.
So the question is, how do I add an event listener to the set of HTML elements found with 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.
source to share
Adding an eventlistener to each one is not practical. Maybe this can help:
document.getElementById('parent').addEventListener('click', function(e){
alert(e.target.value);
})
And if you only want to use getElementsByTagName or getElementsByClassName , then I think you need to iterate over the returned array.
source to share
It's pretty simple as Rutwick Gangurde said. After you get the items, 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 the fiddle: http://jsfiddle.net/wm7p0a77/
source to share
You can use delegates to implement this. Get the parent for these inputs and add an event listener to this parent. This way you just attach one event and use the event bubbles to accomplish your task. In this event listener, you may need to check the target of the event, and if that target is equal to the input element, you can run your logic in that state.
You can do something like this in your event handler function.
// ...
// get event and source element e = e || window.event;
src = e.target || e.srcElement;
if (src.nodeName.toLowerCase() !== "input") {
return;
}
// ...
source to share
you can try like this: first get the whole element of a particular type 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" />
source to share
First use getElementsByClassName instead of getElementsByTagName. Then walk through them by adding an 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
source to share