For loop for HTMLCollection elements

前端 未结 12 1243
挽巷
挽巷 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:47

    There's no reason to use es6 features to escape for looping if you're on IE9 or above.

    In ES5, there are two good options. First, you can "borrow" Array's forEach as evan mentions.

    But even better...

    Use Object.keys(), which does have forEach and filters to "own properties" automatically.

    That is, Object.keys is essentially equivalent to doing a for... in with a HasOwnProperty, but is much smoother.

    var eventNodes = document.getElementsByClassName("events");
    Object.keys(eventNodes).forEach(function (key) {
        console.log(eventNodes[key].id);
    });
    

提交回复
热议问题