...

View Full Version : Removing child elements



Mhtml
02-17-2006, 11:40 PM
Hiya. :)

I'm experimenting with AJAX (www.mithoric.com/new.php), creating a shoutbox but I've run into a problem, other than that I rarely ever code js/dom ever.

The problem is that I'm creating child elements based on an xml document served from a php script. However everytime it is served I'm just appending all the elements to the end of the child list creating copies. So I decided to just remove all the children each time.. But this doesn't seem to be working.


function remove_shouts(){
var shoutbox_div = document.getElementById('shouts');
var shouts = shoutbox_div.childNodes;
for(var i = 0; i < shouts.length; i++){
shoutbox_div.removeChild(shouts.item(i));
}
}

You can see the entire code in www.mithoric.com/rel/js/ajaxshoutbox.js ..

jkd
02-18-2006, 01:14 AM
items.length reflects the current number of items in the collection. removeChild() not only removes a child, but alters the .length property because of this. What I tend to do is the following:



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

Mhtml
02-18-2006, 02:30 AM
Ahh of course, thanks jkd.

liorean
02-18-2006, 04:56 AM
If you want to do it at O(1) instead of O(n) you could do it like this instead:
element.parentNode.replaceChild(element.cloneNode(false),element);

jkd
02-18-2006, 06:02 AM
If you want to do it at O(1) instead of O(n) you could do it like this instead:
element.parentNode.replaceChild(element.cloneNode(false),element);

Slick. :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum