Add Event Listener to Collection of HTML Elements

前端 未结 8 2092
执念已碎
执念已碎 2020-12-03 18:40

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

8条回答
  •  猫巷女王i
    2020-12-03 19:18

    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/

提交回复
热议问题