lampshade
lampshade

Reputation: 2816

Edge 15 throws error when using 'for ... of' on a NodeList

When looking at the ECMAScript compatibility 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?

Upvotes: 3

Views: 1475

Answers (2)

Touffy
Touffy

Reputation: 6561

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.

Upvotes: 3

JLRishe
JLRishe

Reputation: 101748

Edge 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>

Upvotes: 7

Related Questions