Skip to content Skip to sidebar Skip to footer

How To Iterate On HTMLCollection?

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 i

Solution 1:

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) {
  // ...
}

Solution 2:

Just use Array.from(document.getElementsByClassName('node-item')) or the spread operator [...document.getElementsByClassName('node-item')] and use whatever you would use on an array.

Apart from that, you could also use a normal for loop

let nodeItems = document.getElementsByClassName('node-item');
for (let i = 0; i < nodeItems.length; i++) {
    // access current element with nodeItems[i]
}

Solution 3:

You can use spread operator on document.querySelectorAll to have an array.

Here is a snippet:

let nodeItems = [...(document.querySelectorAll('.class1'))];

for (var g of nodeItems) {
  console.log( g.innerHTML ); 
}
<div class='class1'>Text 1</div>
<div class='class1'>Text 2</div>
<div class='class1'>Text 3</div>

Doc: Spread


Post a Comment for "How To Iterate On HTMLCollection?"