Skip to Content »

FlashApe » Simple function for emptying a DIV

 Simple function for emptying a DIV

  • May 24th, 2005
  • 1:14 pm

I was running into a litle trouble trying to empty a DIV of its contents the other day. I was trying to loop over the div’s childNodes array, and doing a removeChild() from each item in the array. Howerver that won’t work…the childNodes array holds ALL nodes, text, elements(which are HTML tags) and the elements’ attributes nodes. So, if you are looping through the childNodes array, and you delete an element, you are going to delete the attributes that are holding other positions in the childNodes array, and javascript will throw an error.
So, here’s a litle function I wrote for clearing out a div. It just checks each node’s nodeType first to see if if is an element node (nodeType = 1) or text node (nodeType = 3) before removing it.
function emptyDiv (divToClear){
var i;
while (i=divToClear.childNodes[0]){
if (i.nodeType == 1 || i.nodeType == 3){
divToClear.removeChild(i);
}
}
}
it feels like there’s probably a better way to pull that loop off…if you do know a better way please leave it in the comments.

5 People had this to say...

Gravatar
  • Geoff
  • February 2nd, 2006
  • 12:57 pm

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

Gravatar
  • Bryan
  • February 2nd, 2006
  • 4:25 pm

Why not just use:
document.getElementById(”divIdGoesHere”).innerHTML = “”;

Gravatar
  • rich
  • February 2nd, 2006
  • 4:38 pm

well, at the time I originally wrote the post, i wanted to stick with using the DOM methods. I would probabyl do that now though…although there was a comment in the original post of a situation where both of those didn’t work exactly the same.

Gravatar

Wow, this blog post had two very handy bits of information for someone learning JS + DOM, the emptyer and the KISS-approved use innerHTML.

Good call!

Gravatar
  • Jason Power
  • April 2nd, 2007
  • 3:18 pm

If I remember correctly innerHtml doesn’t work with divs in IE and you have to do it the DOM way.

Want your say?

* Required fields. Your e-mail address will not be published on this site


You can use the following XHTML tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>