Hi all, right now i'm using div.innerHTML = null to clear all Nodes. i was wondering if anyone has a "cleaner" solution that works just as effectively?
heys cool, im aware of that method however for my case i need to remove nodes within a populated div with about 200-500 nodes so i was abit worried about performance issues.
will div.innerHTML = null be better than using a loop?
Time it, in a realistic situation.
You may find some differences depend on the type of browser but overall you'll find there should be no user-recognizable difference.
If you use the innerHTML method, I'd rather see you set the value to the empty string-
it doesn't amount to much, but it describes what you are doing better.
You aren't removing the property.
That's not going to work, because an element cannot be the reference from which it is removed.
You'll need to use the parent of the element instead.
The code above says: from the parent, take an empty clone of the div, and use it to replace the div.
pmw57 is correct, which reminds me that it is easy to make mistakes when you are typing code.
It's better to test a script you are sure of than to have someone else find the errors...
hey thanks all for the help. but isn't it true that if i have event registers associated with the div, and i use the clone-node-replace method, those events will be lost?
Those events will be lost, so you should use the code that was first suggested by PhilipToop where you keep removing the first child node until there are none left.
It's only the immediate children that have to be removed.
I prefer to check the presence of the firstChild directly:
while( elem.firstChild )
elem.removeChild( elem.firstChild );
There used to be a reason why hasChildNodes was preferred as the condition, but for the life of me it escapes me now.