Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery's after method not working with newly created elements

Insofar as I can tell, the following code should work, creating a <div> element, and then creating a <p> element; the expression should result in a jQuery object with two elements:

$("<div>first element's content</div>").after("<p>second element's content</p>");

However, what I get is very different. The documentation (see the heading "Inserting Disconnected DOM Nodes") tells me the above code should result in a jQuery object, grabbing both HTML snippets and building the two DOM elements. But, what I've gotten, in several different versions of jQuery, all above 1.4, is a jQuery object with only 1 node. However, the following code works just fine, returning (what I believe is) the correct jQuery object, two elements inside:

$("<div></div>").after("<p>second element's content</p>");

And this example works as well:

$("<div></div>").after("<p>second element's content</p>").after("<p>third element's content</p>");

It seems the .after() method works fine if the first DOM node being created is empty, but does not when it is not (irrespective of the contents of subsequent DOM nodes being appended to it).

Am I missing something about jQuery's internals, quirky DOM issues and/or JavaScript peculiarities, or is this simply a jQuery bug that's persisted from version 1.4 on through 1.7?

(Here's a meager JSFiddle demonstrating the issue pretty plainly.)

like image 804
Paul Bruno Avatar asked May 07 '12 21:05

Paul Bruno


2 Answers

This was a known bug in jQuery < 1.9. See http://bugs.jquery.com/ticket/8759

In jQuery >= 1.9, the following information from the upgrade guide should be noted:

Prior to 1.9, .after(), .before(), and .replaceWith() would attempt to add or change nodes in the current jQuery set if the first node in the set was not connected to a document, and in those cases return a new jQuery set rather than the original set. This created several inconsistencies and outright bugs--the method might or might not return a new result depending on its arguments! As of 1.9, these methods always return the original unmodified set and attempting to use .after(), .before(), or .replaceWith() on a node without a parent has no effect--that is, neither the set or the nodes it contains are changed.

like image 113
Heretic Monkey Avatar answered Nov 15 '22 22:11

Heretic Monkey


Use add() to add objects to the collection. I use after() more in DOM elements that already exist or that are cached in a variable, but most of the time, if you work with dynamic markup is more practical to use the equivalent insertAfter().

$("<div>first element's content</div>").add("<p>second element's content</p>");

EDIT:

This works...

var $el = $('<div/>', {
    text: 'hey there'
}).after('<p>Lorem</p>');
like image 45
elclanrs Avatar answered Nov 15 '22 22:11

elclanrs