Javascript 替换 HTMLElement 的所有子元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4991098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:06:38  来源:igfitidea点击:

Replacing all children of a HTMLElement?

javascriptdhtml

提问by Rawler

In my code, I fairly frequently need to replace all children of a certain HTML container with a new list of children.

在我的代码中,我经常需要用新的子项列表替换某个 HTML 容器的所有子项。

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?

执行此操作的最快方法是什么?我目前的方法是将所有新元素收集到 DocumentFragment 中。我发现然后实际替换孩子的唯一方法是一个一个地删除所有孩子,并附加片段。没有更快的方法吗?

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 veryslow CPU so I need to keep full control of any reflows.

注意:解决方案不需要跨浏览器,但最好不需要 3d 方组件,如 jQuery。目标设备是WebKit的一对慢的CPU,所以我需要保持任何回流的完全控制。

回答by Stefan

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 :)

这基本上会以最快的方式删除所有孩子:)

回答by Gibolt

Use modern JS! Directly use removerather than removeChild

使用现代JS!直接使用remove而不是removeChild

while (container.firstChild) {
    container.firstChild.remove();
}

Alternatively:

或者:

let child;
while (child = container.firstChild) {
    child.remove();
}

回答by The Fool

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.

您可以换出整个节点,而不是删除和填充其内容。

oldNode.parentElement.replaceChild(newNode, oldNode)

oldNode.parentElement.replaceChild(newNode, oldNode)

回答by Tom Kay

A possible alternative where setting innerHTML doesn't work:

设置innerHTML不起作用的可能替代方法:

while(container.firstChild)
{
  container.removeChild(container.firstChild);
}
container.appendChild(newChild)