[whatwg/dom] Make NodeIterator Iterable (#704)

[`NodeIterator`](https://developer.mozilla.org/en-US/docs/Web/API/NodeIterator) is an interface designed for simple, linear traversal over the DOM using both pre-defined and custom filters. It is a highly useful tool for reading over nodes when more common tools like [`getElementsByTagName`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName) or [`querySelectorAll`](https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll) don't apply, such as when reading over text or comment nodes.

However, unlike  `HTMLCollection`s and a `NodeList`s, **`NodeIterator`s are not iterable**, and so cannot be used in for-of loops, or other places where iterables are expected.

Given the name, it's reasonable that the `NodeIterator` interface be updated to make it iterable. A potential polyfill/implementation is given here:
```js
if (typeof NodeIterator.prototype[Symbol.iterator] !== 'function') {
  NodeIterator.prototype[Symbol.iterator] = function* () {
    while (true) {
      const next = this.nextNode();
      if (next === null) break;
      yield next;
    }
  };
}
```
And an example usage:
```js
const root = document.body;
const nodeIter = document.createNodeIterator(root, NodeFilter.SHOW_TEXT);
for (const text of nodeIter) {
  /* Perform any operation on all text nodes: */
  console.log(text.data);
}
```

Adding the same iterator to the similar interface [`TreeWalker`](https://developer.mozilla.org/en-US/docs/Web/API/TreeWalker) should also be considered for homogeneity.

The current spec for `NodeIterator` can be found [here](https://dom.spec.whatwg.org/#interface-nodeiterator).

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/dom/issues/704

Received on Sunday, 7 October 2018 03:28:42 UTC