jQuery API

.replaceWith()

.replaceWith( newContent ) Returns: jQuery

Description: Replace each element in the set of matched elements with the provided new content.

  • version added: 1.2.replaceWith( newContent )

    newContentThe content to insert. May be an HTML string, DOM element, or jQuery object.

  • version added: 1.4.replaceWith( function )

    functionA function that returns an HTML string to replace the set of matched elements with.

The .replaceWith() method allows us to remove content from the DOM and insert new content in its place with a single call. Consider this DOM structure:

<div class="container">
  <div class="inner first">Hello</div>
  <div class="inner second">And</div>
  <div class="inner third">Goodbye</div>
</div>

We can replace the second inner <div> with specified HTML:

$('.second').replaceWith('<h2>New heading</h2>');

This results in the structure:

<div class="container">
  <div class="inner first">Hello</div>
  <h2>New heading</h2>
  <div class="inner third">Goodbye</div>
</div>

We could equally target all inner <div> elements at once:

$('.inner').replaceWith('<h2>New heading</h2>');

This causes all of them to be replaced:

<div class="container">
  <h2>New heading</h2>
  <h2>New heading</h2>
  <h2>New heading</h2>
</div>

Or, we could select an element to use as the replacement:

$('.third').replaceWith($('.first'));

This results in the DOM structure:

<div class="container">
  <div class="inner second">And</div>
  <div class="inner first">Hello</div>
</div>

From this example, we can see that the selected element replaces the target by being moved from its old location, not by being cloned.

The .replaceWith() method, like most jQuery methods, returns the jQuery object so that other methods can be chained onto it. However, it must be noted that the original jQuery object is returned. This object refers to the element that has been removed from the DOM, not the new element that has replaced it.

In jQuery 1.4 .replaceWith(), .before(), and .after() can also work on disconnected DOM nodes. For example, with the following code:

$("<div/>").replaceWith("<p></p>");

The .replaceWith() method returns a jQuery set containing only a paragraph.

Examples:

Example: On click, replace the button with a div containing the same word.

<!DOCTYPE html>
<html>
<head>
  <style>
  button { display:block; margin:3px; color:red; width:200px; }
  div { color:red; border:2px solid blue; width:200px; 
        margin:3px; text-align:center; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
	<button>First</button>
  <button>Second</button>

  <button>Third</button>
<script>

    $("button").click(function () {
      $(this).replaceWith("<div>" + $(this).text() + "</div>");
    });
</script>

</body>
</html>

Demo:

Example: Replace all the paragraphs with bold words.

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
	<p>Hello</p>
  <p>cruel</p>

  <p>World</p>
<script>$("p").replaceWith("<b>Paragraph. </b>");</script>

</body>
</html>

Demo:

Example: Replace all the paragraphs with empty div elements.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { border:2px solid blue; margin:3px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
	<p>Hello</p>

  <p>cruel</p>
  <p>World</p>
<script>$("p").replaceWith(document.createElement("div"));</script>

</body>
</html>

Demo:

Example: On click, replace each paragraph with a jQuery div object that is already in the DOM. Notice it doesn't clone the object but rather moves it to replace the paragraph.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { border:2px solid blue; color:red; margin:3px; }
  p { border:2px solid red; color:blue; margin:3px; cursor:pointer; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
	<p>Hello</p>
  <p>cruel</p>
  <p>World</p>

  <div>Replaced!</div>
<script>
    $("p").click(function () {
      $(this).replaceWith($("div"));
    });

</script>

</body>
</html>

Demo:

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for .replaceWith() below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.
  • rnr Tom
    Since IE deletes, rather than replaces element contents if the replacement contents are not valid (e.g. closes too many or not enough <div> tags,) it would be helpful to indicate this in the notes or even the official documentation.

    Please consider this a self-referential note to that effect.</div>
  • Jangla
    Would like to know if there's a way of attaching an animation to this so the replaced element fades in?
  • Xhable
    give it a class where it is hidden, then fade it in.
  • R Jones
    Heads for people using this with Asp.net. The control you replace, it's viewstate information will be gone as well. So, if you use it later in the page it will appear blank. To over come this I used .hide().after( new content ). Give you the same affect, but you keep the viewstate for later use.
  • vanigangadharmuttur
    Hi , My requirement is that on click of edit button , Labels are replaced with Textboxes . Once user Updates in it . Once Update button is clicked , Text boxes are replaced with labels again with updated text .

    But problem is this works only once .

    If User clicks on Edit button again then , Labels are not replaced with textboxes ..
    as labels are virtual labels .

    Step 1 : Click Edit Button
    Step 2 : $("#LabelID").replaceWith("<input id="txtID" type="text" value=""+ LabelCurrText +"">");

    Step 3 : Click Update button
    Step 4 : $("#txt1").replaceWith("<label id="LabelID">"+ LabelUpdText +"</label>");

    Perfect.

    Step 5 : When user again clicks on Edit button
    Step 6 : $("#LabelID").replaceWith("<input id="txtID" type="text" value=""+ LabelCurrText +"">");

    Same code but doesnt work.. or say it doesnt get replaced with . please help.

  • ajpiano
    The proper solution to this in jQuery 1.4.2 is to use
    $("#foo").replaceWith(function(i,html) {
    return "";
    })
  • It's very unespectable that "replaceWith" returns deleted element, not replacement.
  • t3kn0FX
    I'm seeing a similar thing.

    if I have <div id="foo">something here</div>, and I call $("#foo").replaceWith($("#foo").text()), it just removes the div completely, and doesn't replace it with "something here".
  • t3kn0FX
    This appears to work ONLY if the text you are replacing with contains tags around it. Meaning, you can do the example above, but change the replaceWith as follows:
    $("#foo").replaceWith("<faketag>" + $("#foo").text() + "</faketag>");

    Requiring tags around the replacement text seems to be a bug, no?
  • t3kn0FX
    Figured out a way to use it without requiring the fake tags. All you need to do is make the string you want to replace with a textNode. For example:

    $("#foo").replaceWith(document.createTextNode("My Replacement Text"));

    Unfortunately, I think there continues to be an issue with IE6 and IE7 (native, not IE8 compat mode) where it just deletes the element altogether
  • rctay
    Try .text().
  • _Socket
    As of 1.4.1 the only solution to replacing an HTML element with text that I've come up with is: $('#foo').after('My Replacement Text').remove();
  • t3kn0FX
    Thanks _Socket. That's the way jQuery 1.3.2 handled replaceWith, and that's what I wound up doing in the end. Thanks again!

    t3k
  • This just bit me as well. Can someone on the jQuery team at least acknowledge that this is a bug? Is there a fix planned?
  • Not sure the devs will see your comment. See the section above about where bugs should be reported.