JavaScript’s Element.replaceWith() method replaces the Element with a set of Node or string objects.

Syntax

Element.after(parameter1)
Element.after(parameter1, parameter2, /* … , */ parameterN)

Parameters

One or more Node or string objects.

Return value

The replaceWith() method does not have a return value, which means that the method implicitly returns undefined.

Exceptions

HierarchyRequestError DOMException

Thrown when the node cannot be inserted at the specified point in the hierarchy.

Examples

Here are some examples of using the JavaScript replaceWith() method.

Suppose we have the following HTML elements:

<p>The <span>JavaScript Guide</span> is a nice resource to learn JavaScript programming.</p>

We would like to replace the span element with a strong element with JavaScript. What should we do?

We could start by selecting the span element with the querySelector() method and using the replaceWith() method:

let span = document.querySelector('span');
let strong = document.createElement('strong');
strong.textContent = span.textContent;
span.replaceWith(strong);

Here is our HTML now:

<p>The <strong>JavaScript Guide</strong> is a nice resource to learn JavaScript programming.</p>

Browser compatibility

Chrome
Edge
Firefox
Internet Explorer
Opera
Safari
Chrome (Android)
Firefox (Android)
Opera (Android)
Safari (iOS)
Samsung Internet
WebView (Android)
replaceWith() 54 17 49 39 10 54 49 41 10 6.0 54