For loop for HTMLCollection elements

前端 未结 12 1301
挽巷
挽巷 2020-11-22 04:20

I\'m trying to set get id of all elements in an HTMLCollectionOf. I wrote the following code:

var list = document.getElementsByClassName(\"event         


        
12条回答
  •  清歌不尽
    2020-11-22 04:31

    you can add this two lines:

    HTMLCollection.prototype.forEach = Array.prototype.forEach;
    NodeList.prototype.forEach = Array.prototype.forEach;
    

    HTMLCollection is return by getElementsByClassName and getElementsByTagName

    NodeList is return by querySelectorAll

    Like this you can do a forEach:

    var selections = document.getElementsByClassName('myClass');
    
    /* alternative :
    var selections = document.querySelectorAll('.myClass');
    */
    
    selections.forEach(function(element, i){
    //do your stuffs
    });
    

提交回复
热议问题