When I try to build up a sequence of disconnected DOM nodes using .after, it works fine if they are empty:
[14:56:45.186] $('<span></span>').after('<p></p>');
[14:56:45.193] ({0:({}), length:2, prevObject:{0:({}), length:1}, context:(void 0), selector:".after([object Arguments])", 1:({})})
But if I try to add any text in the first node, it fails:
[14:56:41.521] $('<span>test</span>').after('<p></p>');
[14:56:41.525] ({0:({}), length:1})
If I assign that result to a variable and try to inspect it, it appears as if after had never been called at all.
What’s going on here, and how do I work around it?
Edit: For those interested, I ended up writing the following wrappers which seem to be making life much easier for me:
function tag(name) {
return function(contents, options) {
var o = options || {};
var is_array = $.type(contents) === "array";
if (!is_array) {
o.text = contents;
}
result = $('<' + name + ' />', o);
if (is_array) {
$.each(contents, function(i, child) { result.append(child); });
}
return result;
}
}
var span = tag('span');
var div = tag('div');
To clarify your bug — when I run your code in my JavaScript console, I get the following:
According to the jQuery 1.9 upgrade guide:
So: The behavior you’ve observed is a bug which results from using
.after()on a node without a parent. As of 1.9, the jQuery dev team has solved this inconsistency by removing it entirely — using.after()this way should always return the initial node without the<p>after it (fiddle).Workaround:
Push your DOM nodes onto a simple array. Or append them to a parent node, then get all the children: (fiddle)