0

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?

7
  • 5
    When you use for (var x in array), x gets the indexes of the array elements, not the values. Commented Mar 23, 2017 at 2:35
  • 1
    Try putting console.log(par) in your loop and you'll see the problem. Commented Mar 23, 2017 at 2:36
  • 1
    And then you'll also see that this is an example of why you shouldn't iterate over arrays (or array-like objects) with for..in: because you don't just get the array element indices, you get other object property names too. Commented Mar 23, 2017 at 2:37
  • stackoverflow.com/questions/22754315/… Commented Mar 23, 2017 at 2:42
  • @gaazkam—for the reason nnnnnn said, you are getting all enumerable properties of the collection, including inherited ones if there are any, not just the numeric ones (aka indexes). Commented Mar 23, 2017 at 2:44

0