Kardaw
Kardaw

Reputation: 401

.appendchild is not a function - in a "for in" loop

The console throws an error: P[i].appendChild is not a function. The error does not appear if I use the simple "for loop" for( var i=0 ; i<P.length ; ++i ) - instead of the "for-in loop"

HTML:

<div id="container">
  <div class="parent"></div>
  <div class="parent"></div>
  <div class="parent"></div>
</div>

Javascript:

var P = document.getElementsByClassName("parent");
for (var i in P){
  var Child = document.createElement("div");
  Child.class = "child";
  P[i].appendChild(Child);
}

Why I can't use "for-in" and ".appendChild()" at the same time?

Upvotes: 2

Views: 600

Answers (1)

Drew Gaynor
Drew Gaynor

Reputation: 8472

The method getElementsByClassName does not return an array, so P is an object, not an array. Specifically, it is an HTMLCollection with properties other than just nodes, so those properties do not have the method.

You can see that in the example below.

var P = document.getElementsByClassName("parent");
for (var i in P){
  var output = document.createElement('div');
  
  output.innerHTML = "Checking for appendChild on property '" + i + "' on the collection: " + typeof P[i].appendChild;
  document.body.appendChild(output);
}
<div id="container">
  <div class="parent"></div>
  <div class="parent"></div>
  <div class="parent"></div>
</div>

Upvotes: 3

Related Questions