作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个<div>
和一些 child <div>
在里面。例如
<div id="niceParent">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
我尝试使用 forEach
循环遍历它们函数,因为我认为 document.getElementById("niceParent").children
是一个数组,因为我可以使用
console.log(document.getElementById("niceParent").children[1]);
console.log(document.getElementById("niceParent").children[2]);
console.log(document.getElementById("niceParent").children[3]);
console.log(document.getElementById("niceParent").children[4]);
因此我尝试了
document.getElementById("niceParent").children.forEach(function(entry) {
console.log(entry);
});
这不起作用。我明白
TypeError: document.getElementById(...).children.forEach is not a function
作为一种解决方法,我还尝试了一个(更复杂的)for..in
循环:
for (var i in document.getElementById("niceParent").children) {
if (document.getElementById("niceParent").children[i].nodeType == 1) console.log(document.getElementById("niceParent").children[i]);
}
按预期工作。
为什么?
最佳答案
因为 .children
包含 HTMLCollection
[MDN] ,不是数组。 HTMLCollection
对象是一个类似数组的对象,它公开 .length
属性并具有数字属性,就像> 数组,但它不是从 Array.prototype
继承的,因此不是数组。
您可以使用Array.prototype.slice
将其转换为数组:
var children = [].slice.call(document.getElementById(...).children);
<小时/>
ECMAScript 6 引入了一个新的 API,用于将迭代器和类似数组的对象转换为真正的数组:Array.from
[MDN] 。如果可能的话使用它,因为它使意图更加清晰。
var children = Array.from(document.getElementById(...).children);
关于javascript - 为什么 forEach 不适用于 child ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15094886/
我是一名优秀的程序员,十分优秀!