dl101
dl101

Reputation: 147

Indexing in .children list not working as expected

Could anyone please explain why for the given HTML

<body>
  <div id="ustack1">
  Block 1:
  <div id="0"> 0 </div>
  <div id="1"> 1 </div>
  <div id="2"> 2 </div>
  <div id="3"> 3 </div>
  <div id="4"> 4 </div>
  <div id="5"> 5 </div>
  <div id="6"> 6 </div>
  <div id="7"> 7 </div>
  <div id="8"> 8 </div>
  <div id="9"> 9 </div>
  <div id="10"> 10 </div>
</div>

<div id="stagingDiv" style="display:inline-block;">
  Block 2:
</div>
</body>

And the corresponding javascript

var cards = document.getElementById("ustack1").children;

for(i=0;i<cards.length;i++){
  document.getElementById("stagingDiv").appendChild(cards[i]);
}

(As seen in this jsfiddle: https://jsfiddle.net/73oszkj9/ )

that the odd elements are being skipped over?

Upvotes: 3

Views: 40

Answers (2)

jdigital
jdigital

Reputation: 12296

cards is a live HTMLCollection. When you perform the appendChild, you're moving the node to another place in the DOM, which removes it from the collection. One solution is to just iterate over cards until its length is zero:

while(cards.length > 0){
    document.getElementById("stagingDiv").appendChild(cards[0]);
}

Here's an updated fiddle: https://jsfiddle.net/Lkvdep52/

If it makes you feel any better, this is a mistake that many of us have made at one time or another ;-) Using the browser debugger is a good way to understand the underlying cause for problems like this.

Upvotes: 4

Ali Sheikhpour
Ali Sheikhpour

Reputation: 11096

When you use pure appendChil you are cutting the exact element from its parent. Add cloneNode to make a copy of that elements:

var cards = document.getElementById("ustack1").children;
for(i=0;i<cards.length;i++){
  document.getElementById("stagingDiv").appendChild(cards[i].cloneNode(true));
}

At the end you can remove children of first parent if needed.

Upvotes: 0

Related Questions