Replacing all children of an HTMLElement?

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


Use modern JS! Directly use remove rather than removeChild

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

Alternatively:

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

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.