替换HTMLElement的所有子代? [英] Replacing all children of an HTMLElement?
问题描述
在我的代码中,我经常需要用新的子代列表替换某个HTML容器的所有子代.
In my code, I fairly frequently need to replace all children of a certain HTML container with a new list of children.
最快的方法是什么?我当前的方法是将所有新元素收集到DocumentFragment中.我发现实际替换子代的唯一方法是一一删除所有子代,然后附加片段.有没有更快的方法?
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?
注意:解决方案不需要跨浏览器,但最好不要求使用jQuery之类的3d第三方组件.目标设备是非常慢CPU上的WebKit,因此我需要完全控制所有回流.
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.
推荐答案
如果只想替换所有子类型,为什么不将其内容设置为'',然后添加代码:
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:
container.innerHTML = '';
container.appendChild( newContainerElements );
这基本上将以最快的方式删除所有子级:)
that would basically remove all the children in the fastest possible way :)
这篇关于替换HTMLElement的所有子代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!