Element: replaceWith() method
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2018.
TheElement.replaceWith() method replaces thisElement in the children list of its parent with a set ofNode objects or strings. Strings are inserted as equivalentText nodes.
In this article
Syntax
js
replaceWith(param1)replaceWith(param1, param2)replaceWith(param1, param2, /* …, */ paramN)Parameters
param1, …,paramNA set of
Nodeobjects or strings to replace.
Return value
None (undefined).
Exceptions
HierarchyRequestErrorDOMExceptionThrown when the node cannot be inserted at the specified point in the hierarchy.
Examples
>UsingreplaceWith()
js
const div = document.createElement("div");const p = document.createElement("p");div.appendChild(p);const span = document.createElement("span");p.replaceWith(span);console.log(div.outerHTML);// "<div><span></span></div>"replaceWith() is unscopable
ThereplaceWith() method is not scoped into thewithstatement. SeeSymbol.unscopables for more information.
js
with (node) { replaceWith("foo");}// ReferenceError: replaceWith is not definedSpecifications
| Specification |
|---|
| DOM> # ref-for-dom-childnode-replacewith①> |