JS: iterating over result of getElementsByClassName using Array.forEach

前端 未结 11 2076
伪装坚强ぢ
伪装坚强ぢ 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:07

    No. As specified in DOM4, it's an HTMLCollection (in modern browsers, at least. Older browsers returned a NodeList).

    In all modern browsers (pretty much anything other IE <= 8), you can call Array's forEach method, passing it the list of elements (be it HTMLCollection or NodeList) as the this value:

    var els = document.getElementsByClassName("myclass");
    
    Array.prototype.forEach.call(els, function(el) {
        // Do stuff here
        console.log(el.tagName);
    });
    
    // Or
    [].forEach.call(els, function (el) {...});
    

    If you're in the happy position of being able to use ES6 (i.e. you can safely ignore Internet Explorer or you're using an ES5 transpiler), you can use Array.from:

    Array.from(els).forEach((el) => {
        // Do stuff here
        console.log(el.tagName);
    });
    

提交回复
热议问题