For loop for HTMLCollection elements

2019-01-01 01:37发布

I'm trying to set get id of all elements in an HTMLCollection. I wrote the following code:

var list= document.getElementsByClassName("events");
console.log(list[0].id); //first console output
for (key in list){
    console.log(key.id); //second console output
}

But I got the follwoing output in console:

event1
undefined

which is not what I expected. Why is the second console output undefined but the first console output is event1?

10条回答
不再属于我。
2楼-- · 2019-01-01 02:29

There's no reason to use es6 features to escape for looping if you're on IE9 or above.

In ES5, there are two good options. First, you can "borrow" Array's forEach as evan mentions.

But even better...

Use Object.keys(), which does have forEach

Object.keys is essentially equivalent to doing a for... in with a HasOwnProperty, but is mas smoother.

var eventNodes = document.getElementsByClassName("events");
Object.keys(eventNodes).forEach(function (key) {
    console.log(eventNodes[key].id);
});
查看更多
大哥的爱人
3楼-- · 2019-01-01 02:30

I had a problem using forEach in IE 11 and also Firefox 49

I have found a workaround like this

Array.prototype.slice.call(document.getElementsByClassName("events")).forEach(function (key) {
        console.log(key.id);
    }
查看更多
孤独总比滥情好
4楼-- · 2019-01-01 02:33

In ES6, you could do something like [...collection], or Array.from(collection),

let someCollection = document.querySelectorAll(someSelector)
[...someCollection].forEach(someFn) 
//or
Array.from(collection).forEach(someFn)
查看更多
明月照影归
5楼-- · 2019-01-01 02:35

As of March 2016, in Chrome 49.0, for...of works for HTMLCollection:

this.headers = this.getElementsByTagName("header");

for (var header of this.headers) {
    console.log(header); 
}

See here the documentation.

But it only works if you apply the following workaround before using the for...of:

HTMLCollection.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];

The same is necessary for using for...of with NodeList:

NamedNodeMap.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];

I believe/hope for...of will soon work without the above workaround. The open issue is here:

https://bugs.chromium.org/p/chromium/issues/detail?id=401699

Update: See Expenzor's comment below: This has been fixed as of April 2016. You don't need to add HTMLCollection.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator]; to iterate over an HTMLCollection with for...of

查看更多
登录 后发表回答