替换HTMLElement的所有孩子? [英] Replacing all children of a HTMLElement?

查看:111
本文介绍了替换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?

注意:解决方案不需要跨浏览器,但最好不要求使用3d-party组件,如jQuery。目标设备是非常慢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屋!

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