Deleting child nodes of a div node

。_饼干妹妹 提交于 2019-12-08 02:26:56

问题


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:

  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.




回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!