Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing all children of an HTMLElement?

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.

like image 925
Rawler Avatar asked Feb 14 '11 10:02

Rawler


People also ask

How do you get rid of all the children of an element?

To remove all child nodes of an element, you can use the element's removeChild() method along with the lastChild property. The removeChild() method removes the given node from the specified element. It returns the removed node as a Node object, or null if the node is no longer available.

How do you remove all children from parent node?

Child nodes can be removed from a parent with removeChild(), and a node itself can be removed with remove(). Another method to remove all child of a node is to set it's innerHTML=”” property, it is an empty string which produces the same output.

How do you change a child's node?

replaceChild() The replaceChild() method of the Node element replaces a child node within the given (parent) node.

What is the difference between childNodes and children?

The main difference between children and childNodes property is that children work upon elements and childNodes on nodes including non-element nodes like text and comment nodes.


2 Answers

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

like image 167
Stefan Avatar answered Sep 23 '22 01:09

Stefan


2020 Update - use the replaceChildren() API!

Replacing all children can now be done with the (cross-browser supported) replaceChildren() API:

container.replaceChildren(...arrayOfNewChildren); 

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:

container.replaceChildren(); 

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.

like image 20
Mason Freed Avatar answered Sep 22 '22 01:09

Mason Freed