for of loop querySelectorAll

2019-01-19 14:57发布

Mozilla states that "for of loops will loop over NodeList objects correctly". (source: https://developer.mozilla.org/en-US/docs/Web/API/NodeList) However, this doesn't work in Chrome 43. Is this incorrect documentation or a browser bug?

The copied example code used on a page with checkboxes:

var list = document.querySelectorAll( 'input[type=checkbox]' );
for (var item of list) {
  item.checked = true;
}

9条回答
\"骚年 ilove
2楼-- · 2019-01-19 15:15

You can use Array.from

let _list = document.querySelectorAll('input[type=checkbox]');

let list = Array.from(_list);

for (let item of list) {
  //... just like an array
  item.checked = true
}

or more shortly

let list = document.querySelectorAll('input[type=checkbox]');

for (let item of Array.from(list)) {
  item.checked = true
}

Important note Array.from was introduced in Chrome 45 source.

查看更多
我只想做你的唯一
3楼-- · 2019-01-19 15:24

I had this problem. Turns out mine was caused by calling Promise.all() with parameters instead of an array. For example:

Before: Promise.all(p1, p2)

After: Promise.all([p1, p2])

Hope this helps someone.

查看更多
小情绪 Triste *
4楼-- · 2019-01-19 15:26

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];
查看更多
登录 后发表回答