Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to maintain a jQuery reference using replaceWith

If we have an example structure like this:

HTML

<div id="foo">hello foo</div>

JS

var $foo = $('#foo');

and we need to replace the entire HTML markup for that given jQuery/node reference using jQuery's .replaceWith method, what is the best practice to maintain respectively get a new node reference ?

The problem, .replaceWith returns the reference to the old jQuery object (which sounds more or less unreasonable to me). From the docs:

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.

If I go like

$foo = $foo.replaceWith('<div>new content</div>');

I'd like to have that new node referenced/cached in that same variable. Yes you could re-query that newly inserted DOM node, but that seems very clunky in my mind.

Is there any tricky way to achieve that without the need to re-query the DOM ?

Example: http://jsfiddle.net/Lm7GZ/1/

like image 943
Andre Meinhold Avatar asked Oct 01 '12 11:10

Andre Meinhold


People also ask

How to use replaceWith in jQuery?

The replaceWith() method in jQuery is used to replace the selected elements with the new one. This method replaces the matched elements with the specified HTML elements. It returns the replaced elements. This method is similar to the replaceAll() method.

Can we replace in jQuery?

We can replace HTML elements using the jQuery . replaceWith() method. With the jQuery replaceWith() method, we can replace each element in the set of matched elements with the provided new content and return the set of elements that were removed.


2 Answers

Use the .replaceAll() function:

$foo = $('<div>new content</div>').replaceAll($foo);
like image 80
Anthony Grist Avatar answered Sep 28 '22 00:09

Anthony Grist


You can use replaceAll(), swapping the source with the target:

$foo = $('<div>new content</div>').replaceAll($foo);
like image 22
Andy E Avatar answered Sep 28 '22 00:09

Andy E