简体   繁体   English

删除div节点的子节点

[英]Deleting child nodes of a div node

I have following codes to remove child nodes of a div node. 我有以下代码来删除div节点的子节点。 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. 请注意,该代码是针对Greasemonkey脚本的,因此不需要IE支持。

Both bits of code will get the job done but use the DOM approach ( that is while(innerWindowContentBox.hasChildNodes() ... ). while(innerWindowContentBox.hasChildNodes() ...代码都可以完成工作,但是使用DOM方法 (即while(innerWindowContentBox.hasChildNodes() ... )。

Advantages: 好处:

  1. It's quite a bit faster. 它要快很多。 See this speed comparison at jsperf.com . 在jsperf.com上查看此速度比较 On the sample HTML (hundreds of nodes, each with event handlers), the DOM approach was 10 to 20 times faster (so far). 在示例HTML(数百个节点,每个节点都有事件处理程序)上,DOM方法的速度提高了10到20倍(到目前为止)。

  2. It avoids bad habits. 它避免了不良习惯。 Messing about with innerHTML can lead to unexpected bugs, especially on code that needs broad browser support. innerHTML会导致意外错误,尤其是在需要广泛的浏览器支持的代码上。 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. 对于这种特殊情况,这不是问题,但是如果您习惯使用innerHTML操作,它将在某个时候咬住您。

  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. DOM方法可以根据您的需要进行外科手术,因为innerHTML会破坏所有子节点,因此浏览器必须重新构造您希望保留的所有子节点。

Added another test case to the jsPerf benchmark posted by @Brock Adams. 在@Brock Adams发布的jsPerf基准测试中添加了另一个测试用例。 It is slightly faster to test using element.firstChild (at least in Chrome): 使用element.firstChild (至少在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. 当您使用innerHTML时,JS引擎可能并不总是知道DOM的变化,并且您可能会遇到一些奇怪或意外的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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