I\'m trying to set get id of all elements in an HTMLCollectionOf
. I wrote the following code:
var list = document.getElementsByClassName(\"event
You want to change it to
var list= document.getElementsByClassName("events");
console.log(list[0].id); //first console output
for (key in list){
console.log(list[key].id); //second console output
}
you can add this two lines:
HTMLCollection.prototype.forEach = Array.prototype.forEach;
NodeList.prototype.forEach = Array.prototype.forEach;
HTMLCollection is return by getElementsByClassName and getElementsByTagName
NodeList is return by querySelectorAll
Like this you can do a forEach:
var selections = document.getElementsByClassName('myClass');
/* alternative :
var selections = document.querySelectorAll('.myClass');
*/
selections.forEach(function(element, i){
//do your stuffs
});
Alternative to Array.from
is to use Array.prototype.forEach.call
forEach:
Array.prototype.forEach.call(htmlCollection, i => { console.log(i) });
map: Array.prototype.map.call(htmlCollection, i => { console.log(i) });
ect...
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
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)
Eg:-
navDoms = document.getElementsByClassName('nav-container');
Array.from(navDoms).forEach(function(navDom){
//implement function operations
});
On Edge
if(!NodeList.prototype.forEach) {
NodeList.prototype.forEach = function(fn, scope) {
for(var i = 0, len = this.length; i < len; ++i) {
fn.call(scope, this[i], i, this);
}
}
}