Rich Rodecker’s blog on flash, flex, actionscript, javascript, and php, with a dash of randomness
Simple function for emptying a DIV
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.
| Print article | This entry was posted by flashape on May 24, 2005 at 1:14 pm, and is filed under DOM/Javascript. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |

about 4 years ago
while (node.hasChildNodes()) node.removeChild(node.firstChild);
about 4 years ago
Why not just use:
document.getElementById(“divIdGoesHere”).innerHTML = “”;
about 4 years ago
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.
about 3 years ago
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!
about 3 years ago
If I remember correctly innerHtml doesn’t work with divs in IE and you have to do it the DOM way.
about 1 year ago
innerHtml doesn’t work in IE, but textContent does, so you can get around it by using somthing similar to:
var elm = document.getElementById('DivIdHere');
if(window.close){
elm.innerHTML="";
}else{
elm.textContent="";
}
Which will empty your div nicely – though personally I prefer the DOM method suggested by Geoff
about 2 months ago
Thanks! Works like a charm