The replaceWith method

The replaceWith method replaces one element with another. It works similarly to the replaceAll method.

Syntax

The method parameter can be text (possibly with tags), an array, a DOM element, or a jQuery object:

javascript$(What that what what which as how how_replace).replaceWith(than)_replace);

The selected elements will be replaced with the content specified by the text returned by the custom function. The function is called separately for each of the selected elements:

javascript$(selector).replaceWith(function());

Example

Let's replace all paragraphs with class www with a div with text '!!!':

html<p class="www">text</p>
<p class="www">text</p>
<p class="www">text</p>
<p>text</p>
javascript$('p.www').replaceWith('<div>!!!</div>');

HTML the code will look like this:

html<div>!!!</div>
<div>!!!</div>
<div>!!!</div>
<p>text</p>

See also

  • method replaceAll,
    which also replaces some elements with others