According to MDN, a HTMLCollection
, which the children
property of an Element happen to be, is an “array-like object”. OK, so let’s try to iterate through it:
for(var par in document.getElementById("Container").children)
document.getElementById("Results").innerHTML +=
par.id+"<br>"
<div id="Container">
<p id="Par1"></p>
<p id="Par2"></p>
</div>
<p id="Results"></p>
First of all, why am I shown 5 lines instead of 2, one per each paragraph? Then, why do I get undefined
s instead of Par1
and Par2
?
Oddly enough, looping through its indexes works as expected:
var cont = document.getElementById("Container");
for(var i = 0; i < cont.children.length; i++)
document.getElementById("Results").innerHTML +=
cont.children[i].id+"<br>";
<div id="Container">
<p id="Par1"></p>
<p id="Par2"></p>
</div>
<p id="Results"></p>
What do I fail to understand?