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/
Use the
.replaceAll()function: