Reputation: 7910
If I have :
<div id="mc"></div>
and the following ajax.responseText :
<div id="mc">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
and finally my Javascript code :
var div = document.createElement("div");
div.innerHTML = ajax.responseText;
var divChildren = div.children;
for(var i = 0; i < divChildren.length; i++) {
var root = divChildren[i];
var children = root.children;
var documentRoot = document.getElementById(root.id||"$");
if(documentRoot) {
var node = null;
for(var j = 0; j < children.length; j++) {
node = children[j];
documentRoot.appendChild(node);
}
}
}
Why does the result is ? :
<div id="mc">
<div>1</div>
<div>3</div>
<div>5</div>
</div>
Upvotes: 1
Views: 96
Reputation:
This is because children
is a live list, which means when you append one of its elements elsewhere, it will be removed from the list. This messes up forward iteration, unless you decrement the index every time one is removed.
Here are two example solutions...
You would decrement j
...
for(var j = 0; j < children.length; j++) {
node = children[j];
j--;
documentRoot.appendChild(node);
}
But since you're appending all the elements, this doesn't make much sense, since j
is just bouncing back and forth between 0
and -1
.
Because you're adding all the elements, you can simply run the loop as long as there's something at index 0
...
while(children[0]) {
node = children[0];
documentRoot.appendChild(node);
}
Upvotes: 5