For loop for HTMLCollection elements

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

    As of March 2016, in Chrome 49.0, for...of works for HTMLCollection:

    this.headers = this.getElementsByTagName("header");
    
    for (var header of this.headers) {
        console.log(header); 
    }
    

    See here the documentation.

    But it only works if you apply the following workaround before using the for...of:

    HTMLCollection.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
    

    The same is necessary for using for...of with NodeList:

    NamedNodeMap.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
    

    I believe/hope for...of will soon work without the above workaround. The open issue is here:

    https://bugs.chromium.org/p/chromium/issues/detail?id=401699

    Update: See Expenzor's comment below: This has been fixed as of April 2016. You don't need to add HTMLCollection.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator]; to iterate over an HTMLCollection with for...of

提交回复
热议问题