CharacterData: 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.
ThereplaceWith() method of theCharacterData interfacereplaces this node in the children list of its parentwith a set ofNode objects or string.
Strings are inserted asText nodes; the string is being passed as argument to theText() constructor.
In this article
Syntax
js
replaceWith(...nodes)Parameters
nodesOptionalA comma-separated list of
Nodeobjects or strings that will replace the current node.
Note:If no arguments are passed in, this method removes the node from the DOM tree.
Return value
None (undefined).
Exceptions
HierarchyRequestErrorDOMExceptionThrown when the node cannot be inserted at the specified point in the hierarchy.
Examples
html
<p>Some text</p>js
let text = document.getElementById("myText").firstChild;let em = document.createElement("em");em.textContent = "Italic text";text.replaceWith(em); // Replace `Some text` by `Italic text`Specifications
| Specification |
|---|
| DOM> # ref-for-dom-childnode-replacewith①> |