问题
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.
回答1:
Both bits of code will get the job done but use the DOM approach ( that is while(innerWindowContentBox.hasChildNodes() ...
).
Advantages:
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).
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 ofinnerHTML
manipulation.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.
回答2:
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] );
}
回答3:
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.
来源:https://stackoverflow.com/questions/9461301/deleting-child-nodes-of-a-div-node