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 undefineds 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?
for (var x in array),xgets the indexes of the array elements, not the values.console.log(par)in your loop and you'll see the problem.for..in: because you don't just get the array element indices, you get other object property names too.