Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to iterate on HTMLCollection? [duplicate]

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.

like image 591
Fateme Fazli Avatar asked Apr 21 '18 13:04

Fateme Fazli


1 Answers

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) {
  // ...
}
like image 84
Estus Flask Avatar answered Oct 27 '22 03:10

Estus Flask