I have a <div>
with some child <div>
in it. E.g.
<div id="niceParent">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
I tried to loop through them with the forEach
function, because I thought that document.getElementById("niceParent").children
is an array, as I can access the elements with
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]);
Hence I tried
document.getElementById("niceParent").children.forEach(function(entry) {
console.log(entry);
});
which is not working. I get
TypeError: document.getElementById(...).children.forEach is not a function
As a workaround I also tried it with a—much more complicated—for..in
loop:
for (var i in document.getElementById("niceParent").children) {
if (document.getElementById("niceParent").children[i].nodeType == 1) console.log(document.getElementById("niceParent").children[i]);
}
which worked as expected.
Why?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…