For loop for HTMLCollection elements

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

    You can't use for/in on NodeLists or HTMLCollections. However, you can use some Array.prototype methods, as long as you .call() them and pass in the NodeList or HTMLCollection as this.

    So consider the following as an alternative to jfriend00's for loop:

    var list= document.getElementsByClassName("events");
    [].forEach.call(list, function(el) {
        console.log(el.id);
    });
    

    There's a good article on MDN that covers this technique. Note their warning about browser compatibility though:

    [...] passing a host object (like a NodeList) as this to a native method (such as forEach) is not guaranteed to work in all browsers and is known to fail in some.

    So while this approach is convenient, a for loop may be the most browser-compatible solution.

    Update (Aug 30, 2014): Eventually you'll be able to use ES6 for/of!

    var list = document.getElementsByClassName("events");
    for (const el of list)
      console.log(el.id);
    

    It's already supported in recent versions of Chrome and Firefox.

提交回复
热议问题