JS: iterating over result of getElementsByClassName using Array.forEach

前端 未结 11 2186
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 06:42

I want to iterate over some DOM elements, I\'m doing this:

document.getElementsByClassName( \"myclass\" ).forEach( function(element, index, array) {
  //do s         


        
11条回答
  •  被撕碎了的回忆
    2020-11-22 07:08

    You can use Array.from to convert collection to array, which is way cleaner than Array.prototype.forEach.call:

    Array.from(document.getElementsByClassName("myclass")).forEach(
        function(element, index, array) {
            // do stuff
        }
    );
    

    In older browsers which don't support Array.from, you need to use something like Babel.


    ES6 also adds this syntax:

    [...document.getElementsByClassName("myclass")].forEach(
        (element, index, array) => {
            // do stuff
        }
    );
    

    Rest destructuring with ... works on all array-like objects, not only arrays themselves, then good old array syntax is used to construct an array from the values.


    While the alternative function querySelectorAll (which kinda makes getElementsByClassName obsolete) returns a collection which does have forEach natively, other methods like map or filter are missing, so this syntax is still useful:

    [...document.querySelectorAll(".myclass")].map(
        (element, index, array) => {
            // do stuff
        }
    );
    
    [...document.querySelectorAll(".myclass")].map(element => element.innerHTML);
    

提交回复
热议问题