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?

  • 5
    When you use `for (var x in array)`, `x` gets the indexes of the array elements, not the values. – Barmar Mar 23 '17 at 02:35
  • 1
    Try putting `console.log(par)` in your loop and you'll see the problem. – Barmar Mar 23 '17 at 02: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. – nnnnnn Mar 23 '17 at 02:37
  • http://stackoverflow.com/questions/22754315/foreach-loop-for-htmlcollection-elements – b_d Mar 23 '17 at 02: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). – RobG Mar 23 '17 at 02:44
  • Some browsers have implemented *forEach* for NodeLists which will make life easier. There is also [*for..of*](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of), but support is lacking there too. :-( – RobG Mar 23 '17 at 02:46
  • MDN `for..in` do suggest you should using `for` instead to iterate Array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...in_statement – Brian Liu Mar 23 '17 at 02:53

0 Answers0