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/
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.
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.
Use the .replaceAll()
function:
$foo = $('<div>new content</div>').replaceAll($foo);
You can use replaceAll()
, swapping the source with the target:
$foo = $('<div>new content</div>').replaceAll($foo);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With