pacerier — 2010-11-27T15:01:12-05:00 — #1
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?
philiptoop — 2010-11-27T17:01:28-05:00 — #2
pacerier — 2010-11-27T17:20:40-05:00 — #3
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?
paul_wilkins — 2010-11-28T04:31:42-05:00 — #4
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.
mrhoo — 2010-11-28T10:42:27-05:00 — #5
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.
paul_wilkins — 2010-11-28T17:37:27-05:00 — #6
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.
mrhoo — 2010-11-28T19:10:59-05:00 — #7
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...
pacerier — 2010-11-30T09:41:29-05:00 — #8
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?
paul_wilkins — 2010-11-30T16:37:25-05:00 — #9
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.
logic_ali — 2010-11-30T17:49:45-05:00 — #10
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 );
paul_wilkins — 2010-11-30T18:21:45-05:00 — #11
There used to be a reason why hasChildNodes was preferred as the condition, but for the life of me it escapes me now.