Wingroeow
Wingroeow

Reputation: 31

Deleting child nodes of a div node

I have following codes to remove child nodes of a div node. Are both of these codes correct?

while(innerWindowContentBox.hasChildNodes())     
innerWindowContentBox.removeChild(innerWindowContentBox.childNodes[0]);

Other is

innerWindowContentBox.innerHTML = '';

Note that the code is for a Greasemonkey script so IE support is not required.

Upvotes: 2

Views: 681

Answers (3)

slashnick
slashnick

Reputation: 26549

Added another test case to the jsPerf benchmark posted by @Brock Adams. It is slightly faster to test using element.firstChild (at least in Chrome):

while (containerNode.firstChild ) {
    containerNode.removeChild (containerNode.childNodes[0] );
}

Upvotes: 2

Brock Adams
Brock Adams

Reputation: 93553

Both bits of code will get the job done but use the DOM approach ( that is while(innerWindowContentBox.hasChildNodes() ... ).

Advantages:

  1. It's quite a bit faster. See this speed comparison at jsperf.com. On the sample HTML (hundreds of nodes, each with event handlers), the DOM approach was 10 to 20 times faster (so far).

  2. It avoids bad habits. Messing about with innerHTML can lead to unexpected bugs, especially on code that needs broad browser support. At the very least, it destroys event handlers that you may want to preserve. For this particular case, it's not an issue, but it will bite you at some point if you make a habit of innerHTML manipulation.

  3. DOM methods can surgically change just the bit you need, where as innerHTML destroys all child nodes, necessitating the browser to reconstruct any that you wish to preserve.

Upvotes: 2

jamesmortensen
jamesmortensen

Reputation: 34048

Both of those should do roughly the same thing as far as the user goes and as far as the behavior of your app goes.

However, it's worth mentioning that if you're adding elements to a page you should use the former method. When you use innerHTML, the JS engine may not always be aware of the DOM changes, and you might experience some odd or unexpected behavior.

Upvotes: 0

Related Questions