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 content with which to replace the set of matched elements.

The .replaceWith() method removes content from the DOM and inserts 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>

The second inner <div> could be replaced with the specified HTML:

$('div.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>

All inner <div> elements could be targeted at once:

$('div.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>

An element could also be selected as the replacement:

$('div.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>

This example demonstrates 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.

As of jQuery 1.4, .replaceWith() can also work on disconnected DOM nodes. For example, with the following code, .replaceWith() returns a jQuery set containing only a paragraph.:

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

The .replaceWith() method can also take a function as its argument:

$('div.container').replaceWith(function() {
  return $(this).contents();
});

This results in <div class="container"> being replaced by its three child <div>s. The return value of the function may be an HTML string, DOM element, or jQuery object.

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.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 paragraphs with bold words.

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

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

</body>
</html>

Demo:

Example: On click, replace each paragraph with a div that is already in the DOM and selected with the $() function. 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.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:

Example: On button click, replace the containing div with its child divs and append the class name of the selected element to the paragraph.

<!DOCTYPE html>
<html>
<head>
  <style> 
  .container { background-color: #991; }
  .inner { color: #911; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<p>
  <button>Replace!</button>
</p>
<div class="container">
  <div class="inner">Scooby</div>
  <div class="inner">Dooby</div>
  <div class="inner">Doo</div>
</div>

<script>
$('button').bind("click", function() {
  var $container = $("div.container").replaceWith(function() {
    return $(this).contents();
  });

  $("p").append( $container.attr("class") );
});
</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .replaceWith() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .replaceWith()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • Anonymous

    I’m seeing a similar thing.

    if I have something here, and I call $(“#foo”).replaceWith($(“#foo”).text()), it just removes the div completely, and doesn’t replace it with “something here”.

  • Anonymous

    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(“” + $(“#foo”).text() + “”);

    Requiring tags around the replacement text seems to be a bug, no?

  • Anonymous

    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

  • _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();

  • Anonymous

    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

  • http://rapexegesis.com Anonymous

    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?

  • http://keyes.ie/ John Keyes

    Not sure the devs will see your comment. See the section above about where bugs should be reported.

  • Anonymous

    The proper solution to this in jQuery 1.4.2 is to use
    $(“#foo”).replaceWith(function(i,html) {
    return “”;
    })

  • Anonymous

    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(“”);

    Step 3 : Click Update button
    Step 4 : $(“#txt1″).replaceWith(“”+ LabelUpdText +”");

    Perfect.

    Step 5 : When user again clicks on Edit button
    Step 6 : $(“#LabelID”).replaceWith(“”);

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

  • rctay

    Try .text().

  • Candyspecs

    This is what I dynamically added at some point:
    $(“#spinner”).after(<div id=”test”>appended test message</div>);

    In a different scenario, I wanna be able to clear the contents I placed in .after()
    is this something I can do?
    $(“#test”).replaceWith(“

    “);

    Thanks!

  • 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.

  • Jangla

    Would like to know if there's a way of attaching an animation to this so the replaced element fades in?

  • 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.

  • 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.

  • Xhable

    give it a class where it is hidden, then fade it in.

  • Hannes Wurst

    I received an exception with this in 1.4.2:

    $(“.ofc-span”).replaceWith(“@”);

    The workaround was this:

    $(“.ofc-span”).replaceWith(“@”);

    It did not like the “@” character.

    Delete without warning if you like, I don't see why I should register to report a bug.

  • vde

    JQuery: 1.3.2
    Bug: IE
    I have a SSL page and when I replace a button tag by another html code like '<div>OK</div>' I have a popup alert wich says “this page contains a no https element, [...]“.

  • vde75

    to Fix it I use: $('#myolddiv').hide().after('<div>My new Element</div>').remove();

  • davidlegendmc

    If you replace with an object that has a click handler, do you have to do anything to get that listener to bind?

    I'm replacing a link:

    <a class="more">Read more</a>"

    Using:

    &$('.less').replaceWith('<a class="less">Hide</a>');

    But the listener:

    &$("a.less").click(function () { ... }

    …doesn't pick up click events on the new object.

    Any thoughts why?

  • omnomnom

    Working on the same issue right now, have a look at:
    http://api.jquery.com/live/

  • omnomnom

    Working on the same issue right now, have a look at:
    http://api.jquery.com/live/

  • omnomnom

    Yeah, working now with:
    $(“.selector_class”).live('click', function() { alert(“new element clicked”); });

  • omnomnom

    Yeah, working now with:
    $(“.selector_class”).live('click', function() { alert(“new element clicked”); });

  • http://macsdownunder.com davidlegendmc

    Brilliant – thanks. Working for me too now.

  • Chudinov

    replaceWith() function in 1.4.3 is much! slower in Internet Explorer then version 1.4.2

  • Tommy

    Can you replace an entire document with new information?

  • aa

    th