33

I'm writing a script to replace some images with divs in jQuery. I'm currently using the replaceWith() method, which works fine, but returns the original (removed) element instead of the new element.

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.

How can I get a reference to the new DOM element I just created?

Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
C. Ross
  • 31,137
  • 42
  • 147
  • 238
  • 1
    possible duplicate of [how to get actual content of an object after being replaceWith('something') in jquery](http://stackoverflow.com/questions/3573521/how-to-get-actual-content-of-an-object-after-being-replacewithsomething-in-jq) – C. Ross May 25 '11 at 02:06

3 Answers3

52
$.fn.replaceWithPush = function(a) {
    var $a = $(a);

    this.replaceWith($a);
    return $a;
};

See a working demo

qwertymk
  • 34,200
  • 28
  • 121
  • 184
  • Note this only works when a single node is being replaced. If you want to do multiple simultaneous replacements, e.g. $("foobar").replaceWith($a), then only the first one is replaced and the others are dropped, because you can't attach the same DOM node at multiple points in the tree. Evidently the replaceWith("string") variant creates a new DOM node for each replacement, but since it doesn't return those, I think you have to use the find() approach to get them after the fact. – David Soergel Nov 13 '13 at 17:41
21

I believe replaceAll() returns the new content. It has the target and source reversed from replaceWith().

var newobj = $( "<p>New paragraph" ).replaceAll( "#replaceme" );
eaolson
  • 14,717
  • 7
  • 43
  • 58
0

Precede your call to replaceWith() with a jQuery call to find the parent node and then use the parent to find the new node that was inserted with the replaceWith() function.

Here's an example inside the success handler of a $.ajax() function that replaces a form:

success: function(data,textStatus,jqXHR){
    var $li=$form.parents('li');        
    $form.replaceWith(data);
    var $form=$li.find('form');
    //...
},

In this example, there was a unique form for each li. You may need to tailor your approach depending on how you construct your DOM.