替换 HTMLElement 的所有子元素?
在我的代码中,我经常需要用新的子项列表替换某个 HTML 容器的所有子项。
最快的方法是什么?我当前的方法是将所有新元素收集到 DocumentFragment 中。我发现实际替换子项的唯一方法是一一删除所有子项,然后附加片段。难道就没有更快的办法吗?
注意:该解决方案不需要跨浏览器,但最好不需要 3d 方组件,例如 jQuery。目标设备是 WebKit,CPU 速度非常慢,因此我需要完全控制任何回流。
In my code, I fairly frequently need to replace all children of a certain HTML container with a new list of children.
What is the fastest way to do this? My current approach is collecting all new elements into a DocumentFragment. The only way I've found to then actually replace the children is to remove all the children one by one, and append the fragment. Is there no faster way?
Note: the solution needs not be cross-browser, but should preferably not require 3d-party components such as jQuery. The target-device is WebKit on a very slow CPU so I need to keep full control of any reflows.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您只是想替换所有子项,关于类型,为什么不将其内容设置为 '' 然后添加代码:
这基本上会以最快的方式删除所有子项:)
If you simply want to replace all children, regarding of the type, why don't you just set its content to '' and then add your code:
that would basically remove all the children in the fastest possible way :)
2020 更新 - 使用
replaceChildren()
API!现在可以使用(支持跨浏览器) 来替换所有子节点ReplaceChildren() API:
这将在一次操作中执行以下两项操作:a)删除所有现有子级,以及b)追加所有给定的新子级。
您还可以使用相同的 API 仅删除现有子项,而不替换它们:
Chrome/Edge 86+、Firefox 78+ 和 Safari 14+ 支持此功能。它是 完全指定行为。这可能比这里提出的任何其他方法更快,因为删除旧子项和添加新子项是 a) 不需要
innerHTML
完成的,并且 b) 在一步而不是多步。2020 Update - use the
replaceChildren()
API!Replacing all children can now be done with the (cross-browser supported) replaceChildren() API:
This will do both: a) remove all existing children, and b) append all of the given new children, in one operation.
You can also use this same API to just remove existing children, without replacing them:
This is supported in Chrome/Edge 86+, Firefox 78+, and Safari 14+. It is fully specified behavior. This is likely to be faster than any other proposed method here, since the removal of old children and addition of new children is done a) without requiring
innerHTML
, and b) in one step instead of multiple.使用现代 JS!直接使用
remove
而不是removeChild
或者:
Use modern JS! Directly use
remove
rather thanremoveChild
Alternatively:
它不能直接解决问题,但在大多数情况下它是可用的,并且可能是更高效的方法之一。
您可以交换整个节点,而不是删除并填充其内容。
It is not directly solving the question but in most cases it is usable and probably one of the more performant ways.
You can swap out the whole node instead of deleting and filling its content.
设置innerHTML不起作用的可能替代方案:
A possible alternative where setting innerHTML doesn't work:
从最上面的答案来看,我们还可以使用outerHTML 在一行中完成它。
from the top answer, we could also use outerHTML to do it in one line.