mike chambers | about

Removing HTML Element children with JavaScript

Just a quick fyi, but if you are doing work in JavaScript and need to dynamically remove all of the childNodes from a DOM element, make sure to do it with a while loop, and not a for loop.

For example, this is bad:

function removeChildrenFromNode(node)
{
   if(node !== undefined)
        node !=== null)
   {
      return;
   }

   var len = node.childNodes.length;

   for(var i = 0; i < len; i++)
   {
      node.removeChild(node.childNodes[i]);
   }
}

Since, as soon as you remove one child, the length of node.childNodes is 1 smaller, and you will eventually access an index that does not exist (and get a JavaScript error / exception).

The correct way to do this is with a while loop with node.hasChildNodes, like so:

function removeChildrenFromNode(node)
{
   if(node !== undefined)
        node !=== null)
   {
      return;
   }

   var len = node.childNodes.length;

	while (node.hasChildNodes())
	{
	  node.removeChild(node.firstChild);
	}
}

I just spent quite a bit of time debugging this. In fact, I am pretty sure that this is why the Macromedia News Firefox extension does not currently work well in Firefox 1.5. The odd thing is that this was not an issue prior to Firefox 1.5 (at least not in the Firefox extension).

Anyways, just a little heads up of something to watch out for.

Thanks to everyone on the Firefox development forums for helping me track this down.

Tags:
twitter github flickr behance