Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท DOM: Document and Elements

Element.replaceWith()

Reference for replaceWith(): swap an element for one or more nodes or strings in a single step, with parentless behavior, moving rules and comparisons.

replaceWith() removes an element from its parent and puts the nodes or strings you pass in its place, in one step. The new content ends up exactly where the old element was, so the surrounding siblings keep their order.

It is a ChildNode method: elements, text nodes and comment nodes all have it. Strings become text nodes, never HTML.

JavaScript
oldHeading.replaceWith(newHeading);
placeholder.replaceWith("Loaded: ", resultElement);

Try it

Swap an element
Several nodes, strings, and no parent

Syntax

JavaScript
node.replaceWith(...nodesOrStrings)
Name Description
nodesOrStrings Zero or more Node objects or strings. With no arguments the node is simply removed.

Return value: undefined. The method does not return the replaced node, so keep your own reference to it.

Exceptions: a HierarchyRequestError DOMException if the result would be an invalid tree.

Usage notes

  • Parentless nodes are ignored. If the node has no parent, nothing happens and nothing is moved, as the second example shows.
  • Moves existing nodes. A node already in the document is taken from its old place and inserted at the new one.
  • Replacing with itself is harmless. The node ends up where it was.
  • The old node survives. It is detached, not destroyed. You can insert it again later with its listeners and children.
  • Listeners are not transferred. Listeners belong to the old element. The replacement starts with its own, so use event delegation if you swap elements often.
  • Older equivalent. parent.replaceChild(newNode, oldNode) takes exactly one new node and returns the old one. It throws if oldNode is not a child of parent.
  • Not for copying. To put a copy in the document, replace with node.cloneNode(true).
  • Replace the content only. If you want to keep the element but swap what is inside, use replaceChildren() on it.

Browser support

Supported by all current browsers. Very old browsers only have replaceChild().