Add Event Listener to Collection of HTML Elements

Try querySelectorAll method.

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

Which returns a NodeList and you can loop through the array to add the event listeners.


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/


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.

Tags:

Javascript