【发布时间】:2021-03-01 19:50:50
【问题描述】:
我正在尝试将“li”的 HTML 集合转换为数组,但数组中的结果被清空。
我阅读了这个问题并应用了它,但它不起作用。How do I convert a HTMLCollection into an array, without emptying it?
<body>
<ul id="base"></ul>
<script>
const json = [{
"id" : "1",
"date" : "2013/05/05",
},{
"id" : "2",
"date" : "2019/05/05",
}];
for (item of json) {
const list = document.createElement('li');
list.textContent = `${item.date}`;
base.appendChild(list)
}
///the code above works fine.
const base = document.getElementById("base");
const myNodeList = base.getElementsByTagName("li");
console.log(myNodeList);
// gives HTMLCollection
const myArray = Array.from(myNodeList)
// returns empty array
</script>
</body>
结果
我在控制台上测试了相同的代码,它运行良好,如下所示。
【问题讨论】:
-
如果您只想使用数组原型方法,您可以执行以下操作:
Array.prototype.arrayMethod.call(htmlCollection, () => {});arrayMethod 可以是您可以在数组上调用的任何方法,例如 fllter、forEach、map 等。 HTML 集合是document.getElementsByTagName返回的 NodeList。如果您要处理文档中的大量节点,则性能会好得多。
标签: javascript dom