how to iterate on HTMLCollection? [duplicate]

2020-02-14 02:13发布

问题:

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.

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


回答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]
}


回答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