Replacing all children of a HTMLElement?

血红的双手。 提交于 2019-12-03 14:37:49

问题


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.


回答1:


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




回答2:


Use modern JS! Directly use remove rather than removeChild

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

Alternatively:

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



回答3:


A possible alternative where setting innerHTML doesn't work:

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



回答4:


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)



来源:https://stackoverflow.com/questions/4991098/replacing-all-children-of-a-htmlelement

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!