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.