Reputation: 779
I have the following code and I am trying to remove dynamically all the "container" elements from an element supercontainer
dynamically.Since nodeList is live the following code should remove the container1
as well as container2
but it isn't.Can any one tell why?how do I improve this code so as to dynamically remove all childNodes?
<html><body></body>
<script type="text/javascript">
var supercontainer=document.createElement("div");
var container2=document.createElement("div");
var container1=document.createElement("div");
var b=document.createElement("div");
var c=document.createElement("div");
var d=document.createElement("div");
b.appendChild(document.createTextNode("book1"));
c.appendChild(document.createTextNode("book2"));
d.appendChild(document.createTextNode("book3"));
container1.appendChild(b);
container1.appendChild(c);
container1.appendChild(d);
container2.appendChild(document.createTextNode("i am container2"));
supercontainer.appendChild(container1);
supercontainer.appendChild(container2);
document.body.appendChild(supercontainer);
function removeContainers(){
var j=0;
for(i=0;i<supercontainer.childNodes.length;i++){
supercontainer.removeChild(supercontainer.childNodes[j]);
}
}
removeContainers();
</script>
</html>
Upvotes: 0
Views: 327
Reputation: 75317
Because your loop is missing elements.
In the first iteration, you remove the element that is first in the NodeList
. As you said, NodeList
's are live, so this element is removed from the NodeList
you're iterating over as well. This shifts the element that was [1]
'st to [0]
th.
The loop then increments i
to [1]
, so you ignore the element that is now 0 in the list.
Instead;
while (supercontainer.childNodes.length) {
supercontainer.removeChild(supercontainer.childNodes[0]);
}
Upvotes: 0
Reputation: 388316
In your loop,
The solution is to keep the loop count in a separate counter variable like length
Use
function removeContainers(){
var j=0, len = supercontainer.childNodes.length;
for(i=0;i<len;i++){
supercontainer.removeChild(supercontainer.childNodes[j]);
}
}
Demo: Fiddle
Upvotes: 2