javascript - working with nodeList "childNodes" of element.Why isn't the container2 being removed? -


i have following code , trying remove dynamically "container" elements element supercontainer dynamically.since nodelist live following code should remove container1 container2 isn't.can 1 tell why?how improve code dynamically remove 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 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> 

in loop,

  1. i = 0; nodes.length 2
  2. first item removed becomes 1 , length becomes 1
  3. the loop terminating condition fails

the solution keep loop count in separate counter variable length

use

function removecontainers(){     var j=0, len = supercontainer.childnodes.length;     for(i=0;i<len;i++){         supercontainer.removechild(supercontainer.childnodes[j]);     } } 

demo: fiddle


Comments

Popular posts from this blog

c# - Operator '==' incompatible with operand types 'Guid' and 'Guid' using DynamicExpression.ParseLambda<T, bool> -