Add Event Listener to Collection of HTML Elements

前端 未结 8 2076
执念已碎
执念已碎 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条回答
  •  时光取名叫无心
    2020-12-03 19:25

    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);
    }
    
    

提交回复
热议问题