I am used to being able to work with templated content that is disconnected from the DOM using .before, .after, or .replaceWith in jQuery 1.8+. With 1.9 it seems we have completely lost the ability to manipulate disconnected nodes with these methods as they always return the unmodified original set.
For example:
// prepare some disconnected content, e.g. compiling templates
var $node = $('<div>before</div>');
// later do some calculations and have a need to splice some disconnected content together
var $after = $('<div class="green">after</div>');
$node.after($after)
// Add to the DOM
$('.result').append($node);
Here are fiddles demonstrating how this breaks:
- 1.8.3 (expected behavior): http://jsfiddle.net/octatone/zgynM/
- 1.9 (no longer works): http://jsfiddle.net/octatone/hTp27/
I am fine with jQuery removing this behavior for consistency, but there has to be a work around. I do not want, nor should I have to, connect disconnected nodes to the dom in order to manipulate them in this fashion.
How do we work around the new .after, .before and .replaceWith behaviors in jQuery 1.9?
Instead of trying to append to the nonexistent DOM, just add to the jQuery selector (i.e. use
.addinstead). This seems to work:http://jsfiddle.net/hTp27/3