JavaScript: removeChild HOWTO
I experienced a small issue this morning when trying to remove all the children from a <td> using the following:
// cells[i] is a td in a table
var kids = cells[i].childNodes;
for (j=0; j < kids.length; j++) {
cells[j].removeChild(kids[j]);
}
This (for some reason) doesn't work. So, in the interest of helping others and getting picked up by Google, here's the solution (actually found via Google).
while (cells[i].childNodes[0]) { cells[i].removeChild(cells[i].childNodes[0]); }
HTH!
<code>for (j=kids.length; j >= 0; j--) ....</code>
or something like that.
Posted by Lance on June 10, 2003 at 06:20 PM MDT #
Posted by 216.208.134.99 on November 23, 2004 at 07:23 PM MST #
As you remove things from the beginning, the length of the array remains the same, but the number of items that actually exits decreases. So let's say you have a div with 3 spans inside it - call them A, B, and C - here's what will happen with the first script:
j = 0 Remove 0th span, A kids is still the same now there are only 2 spans, B and C
j = 1 Remove 1st span This is really span C, because all information has been moved back one kids is still the same now there's only one span, C
j = 2 Remove the 2nd span This causes the error. You there's nothing to remove at the second span. It's already gone. You're trying to remove C which is at 0, not at 2.
So you can go backwards as said before, or continuously remove from the 0th position until there's nothing left. Just in case you cared.
Posted by laxwy on July 17, 2005 at 03:31 AM MDT #
Posted by Jude on October 04, 2005 at 12:48 AM MDT #
Posted by Stewart Johnson on April 02, 2006 at 02:37 PM MDT #
Posted by Julian Harris on July 13, 2006 at 04:39 PM MDT #
Posted by Julian on July 13, 2006 at 05:27 PM MDT #
for bether compatibility u must always use 'getElementById'
Posted by papasound on July 28, 2006 at 08:46 AM MDT #