简体   繁体   中英

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.

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.

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] );
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM