how to iterate on HTMLCollection?

Fateme Fazli picture Fateme Fazli · Apr 21, 2018 · Viewed 23k times · Source

I have some elements in my HTML with class node-item, I access them in my component using:

let nodeItems = document.getElementsByClassName('node-item');

and when I log nodeItems it gives me a HTMLCollection[] with length 4.

I tried many ways but still can't iterate on nodeItems:

1- first try:

let bar = [].slice.call(nodeItems);
for (var g of bar){
    console.log(g); //gives me nothing
} 

2- second try:

for(let c of <any>nodeItems) {
    console.log(c); //gives me nothing
}

And I tried array iteration and object iteration but still undefined or error. also tried:

let nodeItems = document.querySelector(selectors);

But same problems.

Answer

Estus Flask picture Estus Flask · Apr 21, 2018

nodeItems is HTMLCollection, which is array-like object.

It is iterable in modern browsers. Iterators are supported with downlevelIteration compiler option enabled, in this case it will be:

const nodeItems = document.getElementsByClassName('node-item');

for (const c of nodeItems) {
  // ...
}

Iterables can be polyfilled in older browsers. core-js provides polyfills for DOM iterables.

Otherwise nodeItems can be converted to array and iterated as usual:

const nodeItems = Array.from(document.getElementsByClassName('node-item'));

for (const c of nodeItems) {
  // ...
}