[英]Remove child nodes (or elements) or set innerHTML=“”?
When clearing HTML elements such as select boxes, tables, or lists, is it better/faster to remove the nodes (eg, select.options.remove(i)
, table.deleteRow(i)
) or just empty the innerHTML (eg, select.innerHTML = ""
)? 清除HTML元素(如选择框,表或列表)时,删除节点(例如, select.options.remove(i)
, table.deleteRow(i)
)或仅清空innerHTML(例如, select.innerHTML = ""
)? Or does it matter? 或者重要吗?
An example case would be reinitializing a table. 一个示例案例是重新初始化表。 A specific select field's value should load different values for a subsequent HTML table. 特定选择字段的值应为后续HTML表加载不同的值。 When the select value changes, the table needs to be reinitialized. 当选择值更改时,需要重新初始化表。
In IE you cannot set the innerHTML of a select element . 在IE中,您无法设置select元素的innerHTML 。 So for a cross-browser solution the only way is to add/remove child nodes. 因此,对于跨浏览器解决方案,唯一的方法是添加/删除子节点。
I made a new test that isn't broken. 我做了一个没有破坏的新测试。
http://jsperf.com/innerhtml-vs-removechild/67 http://jsperf.com/innerhtml-vs-removechild/67
It's not perfect either since part of the sample setup is part of the test so this might skew the results. 它并不完美,因为部分样本设置是测试的一部分,因此这可能会使结果产生偏差。
This gives that innerHTML
is faster but I don't know by how much. 这给了innerHTML
更快,但我不知道多少。
Per this conversation here: What is the best way to empty an node in JavaScript 根据这里的对话: 在JavaScript中清空节点的最佳方法是什么
It appears that the while (elm.firstChild) {elm.removeChild(elm.firstChild);}
approach got the the best results across browsers in this test . 似乎while (elm.firstChild) {elm.removeChild(elm.firstChild);}
方法在此测试中获得了跨浏览器的最佳结果。
(Would have put this as a comment instead of an answer, but the comments are coming in awful fast, so I didn't want it to get lost.) (本来可以把它作为评论而不是答案,但评论的速度很快,所以我不想让它迷路。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.