如何在HTMLCollection上进行迭代

如何在HTMLCollection上进行迭代

本文介绍了如何在HTMLCollection上进行迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的HTML中具有类node-item的一些元素,我可以使用以下方式在组件中访问它们:

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

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

当我登录nodeItems时,它会给我一个长度为4的HTMLCollection[].

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

我尝试了很多方法,但是仍然无法在nodeItems上进行迭代:

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

1-首先尝试:

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

2秒尝试:

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

我尝试了数组迭代和对象迭代,但是仍然是undefinederror.还尝试过:

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

let nodeItems = document.querySelector(selectors);

但是同样的问题.

推荐答案

nodeItemsHTMLCollection,它是类似数组的对象.

nodeItems is HTMLCollection, which is array-like object.

在现代浏览器中它是可迭代的.在启用 downlevelIteration编译器选项的情况下,支持迭代器.将是:

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

可迭代项可以在较旧的浏览器中进行填充. core-js为DOM可迭代项提供 polyfills .

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

否则,nodeItems可以转换为数组并照常进行迭代:

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

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

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

这篇关于如何在HTMLCollection上进行迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 20:03