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
?
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
'sforEach
as evan mentions.But even better...
Use
Object.keys()
, which does haveforEach
Object.keys
is essentially equivalent to doing afor... in
with aHasOwnProperty
, but is mas smoother.I had a problem using forEach in IE 11 and also Firefox 49
I have found a workaround like this
In ES6, you could do something like
[...collection]
, orArray.from(collection)
,As of March 2016, in Chrome 49.0,
for...of
works forHTMLCollection
:See here the documentation.
But it only works if you apply the following workaround before using the
for...of
:The same is necessary for using
for...of
withNodeList
:I believe/hope
for...of
will soon work without the above workaround. The open issue is here: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