在JavaScript中清空节点的最佳方法是什么? [英] What is the best way to empty a node in JavaScript

查看:82
本文介绍了在JavaScript中清空节点的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含很长缩略图列表的图库。为了防止DOM被节点填满,我正在重用它们。从DOM中删除节点的最佳方法是什么(不使用库)?



使用 innerHTML =将解析并创建一个新的空文本节点,但循环和删除子将导致重排?

解决方案

使用 innerHTML =将确保您调用它的元素根本没有子节点(不创建任何新节点)。它是可靠的跨浏览器(即使它最近才进入。只要确保你的测试自我检查;对于时间,这个答案在其中进行了一次测试,未能仔细检查,并且存在缺陷。


I have a gallery with a long list of thumbnails. To prevent the DOM to be filled up with nodes, I am reusing them. What is the best way to remove the nodes from the DOM (without using a library)?

Using innerHTML = "" will parse and create a new empty text node, but looping and removing child will cause reflows?

解决方案

Using innerHTML = "" will make sure the element on which you call it has no child nodes at all (doesn't create any new nodes). It's reliable cross-browser (even though only recently did it make its way into a specification, which is referenced from the HTML5 spec) provided you don't have any references to the nodes within the element that are being replaced (if you do, there's an IE bug), and is probably fairly efficient.

Your other choice is to use removeChild, but that involves potentially repeated function calls into the DOM:

// assuming elm is the element
while (elm.firstChild) {
   elm.removeChild(elm.firstChild);
}

If I had to guess, I'd guess that that was much less efficient than setting innerHTML. And apparently that's true, to varying degrees (the loop above is "firstChild" in the test list, vs. "innerHTML"):

If you're really worried about which is more efficient (which, barring your seeing an actual problem, might well be premature optimization), test your specific code on your target browsers. Just be sure your test double-checks itself; for a long time this answer had a test in it that failed to double-check itself, and was flawed.

这篇关于在JavaScript中清空节点的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆