Are HTMLCollection and NodeList iterables?

前端 未结 4 1973
失恋的感觉
失恋的感觉 2020-12-01 23:35

In ES6, an iterable is an object that allows for... of, and has a Symbol.iterator key.

Arrays are iterables, as are Sets and Maps. The question is: are

相关标签:
4条回答
  • 2020-12-01 23:58

    Unfortunately, not yet. But until they are, you can easily polyfill them like so:

    HTMLCollection.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
    
    0 讨论(0)
  • 2020-12-02 00:02

    Symbol.iterator support for NodeList, HTMLCollection, DOMTokenList, and DOMSettableTokenList was discussed and added to the WHATWG's DOM spec last year.

    0 讨论(0)
  • 2020-12-02 00:14

    For anyone arriving here from trying to iterate on NodeList using TypeScript. I found this issue with the fix https://github.com/microsoft/TypeScript/issues/4947 and this is the tsconfig.json you'll need for it:

    {
      "compilerOptions": {
        "lib": ["es2017", "dom", "dom.iterable"],
        "downlevelIteration": true
      }
    }
    

    The problem error I was getting:

    Type 'NodeListOf<Element>' is not an array type.
    

    And this was the code that was triggering that problem:

    [...document.querySelectorAll('#md-view a')]
    
    0 讨论(0)
  • 2020-12-02 00:16

    As greiner pointed out, native Symbol.iterator support for NodeList was added to the WHATWG's DOM spec in 2014.

    Unfortunately, Chrome 51 is the first version of Chrome to support it, and its Beta has only just been released at the time of writing this answer. Also, there's no support in any version of Internet Explorer or Edge.

    To add Symbol.iterator support for NodeList in all browsers to your code, just use the following polyfill :

    NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
    
    0 讨论(0)
提交回复
热议问题