EDIT: To change the original set, you can .push() add a DOM element (not a jQuery object) to the set.
var elementToAdd = $('<h3>').html('header'); var p = $('<p>').html('hello world');
Instead of .after() use the jQuery .add() method.
var elementToAdd = $('<h3>').html('header'); var p = $('<p>').html('hello world');
This will add him as a sibling as you want.
It returns a new jQuery object with both elements as siblings. Since it does not modify the original object, you need to either call it in .append() or save the result in the added variable.
EDIT: (As pointed out in another answer, you can now use after() as add() since it returns a new set and does not change the original.)
To explain why this is due to the fact that the jQuery object is an array of DOM elements. The DOM element may be the only element with nested descendants, but not with two siblings. Therefore, when you execute .after() , you are trying to add a sibling to each individual element of the array.
To deal with siblings, jQuery stores them as additional elements in its array.
Therefore, when you create a jQuery object by passing two or more sibling elements, it breaks them into pieces and makes them separate elements in the array.
var $obj = $("<div>div element</div> <span>span element</span>");
This will give you a jQuery object with an array of 2 elements.
$obj[0] is the <div> element $obj[1] is the <span> element
So, if you were to create them separately, you would need to use .add() to add a new element to the array.
var $obj = $("<div>div element</div>"); $obj[0] is the <div> var $span = $("<span>span element</span>"); $obj = $obj.add( $span ); $obj[0] is the <div> $obj[1] is the <span>