I have this code (running jQuery 1.4.2)
var elementToAdd = $('<h3>').html('header');
var p = $('<p>').html('hello world');
elementToAdd.after(p);
$('div#content').append(elementToAdd);
However, the output is
<div id="content">
<h3>header</h3>
</div>
The paragraph “Hello world” is not added.
What am I doing wrong?
I have been trying out some variations:
This does not work either:
var elementToAdd = $('<div>Header</div>');
var p = $('<p>hello world</p>');
elementToAdd.after(p);
or this:
var elementToAdd = $('<h3>header</h3>').after('<p>hello world</p>');
But this works (on Firefox, at least):
var elementToAdd = $('<div>').after('<h3>header</h3>').after('<p>hello world</p>');
Why?
EDIT: To modify the original set, you can
.push()a DOM element (not a jQuery object) into the set.Instead of
.after(), use jQuery’s.add()method.This will append it as a sibling like you want.
It returns a new jQuery object with both elements as siblings. Because it doesn’t modify the original object, you need to either call it in the
.append()or store the result in a variable to append.EDIT: (As noted in another answer, you can now use
after()likeadd(), in that it returns a new set and doesn’t modify the original.)To explain why, this is because a jQuery object is an Array of DOM elements. A DOM element can be a single element with nested descendants, but not two siblings. So when you do
.after(), you’re trying to add a sibling to each single element in the array.To deal with siblings, jQuery has them stored as additional items in its Array.
So when you create a jQuery object by passing 2 or more sibling elements, it splits them apart, and makes them separate items in the Array.
This will give you a jQuery object with an Array of 2 items.
So if you were to create them separately, you would need to use
.add()to add the new item to the Array.