DocumentFragment: replaceChildren() method
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
The DocumentFragment.replaceChildren()
method replaces the
existing children of a DocumentFragment
with a specified new set of children. These
can be string or Node
objects.
Syntax
replaceChildren(param1)
replaceChildren(param1, param2)
replaceChildren(param1, param2, /* …, */ paramN)
Parameters
param1
, …,paramN
-
A set of
Node
objects or strings to replace theDocumentFragment
's existing children with. If no replacement objects are specified, then theDocumentFragment
is emptied of all child nodes.
Return value
None (undefined
).
Exceptions
HierarchyRequestError
DOMException
-
Thrown when the constraints of the node tree are violated.
Examples
Emptying a document fragment
replaceChildren()
provides a very convenient mechanism for emptying a document fragment
of all its children. You call it on the document fragment without any argument specified:
let fragment = new DocumentFragment();
let div = document.createElement("div");
let p = document.createElement("p");
fragment.append(p);
fragment.prepend(div);
fragment.children; // HTMLCollection [<div>, <p>]
fragment.replaceChildren();
fragment.children; // HTMLCollection []
Specifications
Specification |
---|
DOM Standard # ref-for-dom-parentnode-replacechildren① |
Browser compatibility
BCD tables only load in the browser