goog.dom.removeChildren()

488 views
Skip to first unread message

Jay Young

unread,
Nov 4, 2010, 12:15:26 PM11/4/10
to Closure Library Discuss
I'm curious why goog.dom.removeChildren goes through the hassle of
explicitly removing all children instead of simply doing

node.innerHTML = ''; // Removes all child nodes and creates an empty
text node.
node.removeChild(node.firstChild); // Removes empty text node

Is there a cross-browser issue here? I guess I always assumed that if
innerHTML can be used to build up DOM it would be just as useful in
removing it.

Have a great day.

Emil A Eklund

unread,
Nov 4, 2010, 1:22:20 PM11/4/10
to closure-lib...@googlegroups.com

setting innerHTML destroys all children, removing them using
removeChild does not. Thus if there is a reference to one of the nodes
the first method (setting innerHTML) would invalidate that reference
while the second method does not and thus allows the node to be
reused.

Consider an example:

<div id="foo"><span id="bar">sdjasd</span></div>

var fooEl = document.getElementById('foo');
var barEl = document.getElementById('bar');

goog.dom.removeChildren(fooEl);
document.body.appendChild(barEl);

In this example the bar span is moved from the foo div to the body.
Had removeChildren been implementyed by setting innerHTML this would
no longer work.

--
Emil

Daniel Steigerwald

unread,
Nov 4, 2010, 1:29:57 PM11/4/10
to Closure Library Discuss
innerHTML destroys elements, then registered listeners will not be
removed.

Jay Young

unread,
Nov 4, 2010, 2:44:55 PM11/4/10
to Closure Library Discuss
On Nov 4, 1:29 pm, Daniel Steigerwald <dan...@steigerwald.cz> wrote:
> innerHTML destroys elements, then registered listeners will not be
> removed.

Event listeners should be removed before destroying the DOM. That's
not really an issue.

I hadn't thought about the reuse of elements, though, as Emil pointed
out. That's certainly a good reason. I only really ever use
innerHTML for getting rid of throw-away content (after cleaning up
listeners).

Thanks for the clarification.
Reply all
Reply to author
Forward
0 new messages