I\'m trying to set get id of all elements in an HTMLCollectionOf
. I wrote the following code:
var list = document.getElementsByClassName(\"event
You can't use for
/in
on NodeList
s or HTMLCollection
s. However, you can use some Array.prototype
methods, as long as you .call()
them and pass in the NodeList
or HTMLCollection
as this
.
So consider the following as an alternative to jfriend00's for loop:
var list= document.getElementsByClassName("events");
[].forEach.call(list, function(el) {
console.log(el.id);
});
There's a good article on MDN that covers this technique. Note their warning about browser compatibility though:
[...] passing a host object (like a
NodeList
) asthis
to a native method (such asforEach
) is not guaranteed to work in all browsers and is known to fail in some.
So while this approach is convenient, a for
loop may be the most browser-compatible solution.
Update (Aug 30, 2014): Eventually you'll be able to use ES6 for/of!
var list = document.getElementsByClassName("events");
for (const el of list)
console.log(el.id);
It's already supported in recent versions of Chrome and Firefox.