Visit Mozilla.org

Talk:DOM:element.childNodes

From MDC

Using childNodes to loop doesn't seam to work as expected. Example: (This should remove all children from the box, but it doesn't)

   var $box    = document.getElementById( $id );   //get our Box
               
   //Cycle all The Children
   var $kids = $box.childNodes;
   for( i=0; i < $kids.length; i++ ) {
       //Quick test
       var $jr = $kids[i];
       //This should remove everything from the box
       $box.removeChild( $jr );
    }
This doesn't work because the childNodes array is "live"; every time you change it the value of $kids changes and all the items are re-indexed to zero. You should remove items from the end of the childNodes array by initializing i=$kids.length-1 and doing i-- for each loop to get the desired effect. An even better choice (untested, I'm not sure whether this works with liveness or not) would be to do |for (var i in $kids.childNodes) $box.removeChild($kids[i]);|, but don't blindly believe me because I'm not completely familiar with the DOM's minutiae. --Waldo 21:26, 10 November 2005 (PST)