When looking at the ECMAScript patibility table, it says that Edge 15 and Edge 16 support for ... of
loops.
However, when I run this code:
const list = document.querySelectorAll('[data-test]');
console.log(list);
for (const item of list) {
console.log(item);
}
<div data-test></div>
<div data-test></div>
<div data-test></div>
<div data-test></div>
<div data-test></div>
When looking at the ECMAScript patibility table, it says that Edge 15 and Edge 16 support for ... of
loops.
However, when I run this code:
const list = document.querySelectorAll('[data-test]');
console.log(list);
for (const item of list) {
console.log(item);
}
<div data-test></div>
<div data-test></div>
<div data-test></div>
<div data-test></div>
<div data-test></div>
It works in Chrome and Firefox, but not in Edge. Instead it says:
Object doesn't support property or method 'Symbol.iterator'.
As I understand it, NodeList
actually should support it, right?
Here's a fildde to try it yourself: Test it online
Can somebody explain the problem or the mistake here?
Share Improve this question edited Aug 31, 2018 at 9:29 lampshade asked Nov 14, 2017 at 13:41 lampshadelampshade 2,8167 gold badges46 silver badges89 bronze badges 3-
1
Edge does support
for... of
. It would seem that it doesn't support iterators onNodeList
s. – JLRishe Commented Nov 14, 2017 at 13:47 - Have you considered loading a polyfill? This kind of thing is what they are best at. – loganfsmyth Commented Nov 14, 2017 at 17:19
- @loganfsmyth Good point. I'm also considering the suggested solution which is like a polyfill but for this specific problem only. – lampshade Commented Nov 14, 2017 at 22:18
2 Answers
Reset to default 7Edge does support for... of
.
It would seem that it doesn't support iterators on NodeLists. Not all array-like objects support iterators and I'm not sure whether there is any standard saying that NodeLists have to.
In any case, it's easy enough to get for ... of
to work with them:
const list = document.querySelectorAll('[data-test]');
for (const item of Array.from(list)) {
console.log(item);
}
<div data-test>a</div>
<div data-test>b</div>
<div data-test>c</div>
<div data-test>d</div>
<div data-test>e</div>
If for..of
is supported but Edge 15 forgot to add the behavior to NodeList, you could polyfill it yourself with very little code:
NodeList.prototype[Symbol.iterator] = function* () {
for(var i = 0; i < this.length ; i++) {
yield this[i]
}
}
To answer the other question (is it defined as iterable in the spec?) the answer is yes:
The DOM spec defines NodeList as:
interface NodeList {
getter Node? item(unsigned long index);
readonly attribute unsigned long length;
iterable<Node>;
};
Note the third property, iterable<Node>;
. Looking it up in the WebIDL spec:
In the ECMAScript language binding, an interface that is iterable will have “entries”, “forEach”, “keys”, “values” and @@iterator properties on its interface prototype object.
It seems that Edge doesn't implement any of that.