kbirk
kbirk

Reputation: 4022

Using jQuery to append as sibling rather than child element

I can't seem to find the functionality that I'm looking for. I need to append some DOM elements, as siblings, to a disconnected node.

Seems pretty straight forward, and according to the jQuery documentation I should be able to do this with either .after() or .add(), but neither word:

var $set = $('<div class="parent"></div>');
    $set.add('<div class="child"></div>');
    $set.add('<div class="child"></div>');
    $set.add('<div class="child"></div>');
$('body').append($set);

http://jsfiddle.net/kh9Uj/17/ and http://jsfiddle.net/kh9Uj/19/

It works if I chain them using .add():

$('<div class="parent"></div>')
    .add('<div class="child"></div>')
    .add('<div class="child"></div>')
    .add('<div class="child"></div>')
.appendTo('body');

http://jsfiddle.net/kh9Uj/23/

But not with .after(), and in my application I don't have the option on chaining them. How can I do this?

Edited to fix class / id issue.

Upvotes: 0

Views: 1412

Answers (1)

epascarello
epascarello

Reputation: 207557

set does not update the variable

var $set = $('<div id="parent">0</div>');
$set = $set.add('<div id="child1">1</div>');
$set = $set.add('<div id="child2">2</div>');
$set = $set.add('<div id="child3">3</div>');
$('body').append($set);

Chaining works because you are adding them to the same object.

var $set = $('<div id="parent">0</div>')          //first element
               .add('<div id="child1">1</div>')   //second element in object
               .add('<div id="child2">2</div>')   //third
               .add('<div id="child3">3</div>');  //fourth
$('body').append($set);

BUT add is not adding it to parent. It is adding it as "siblings" when you append it.

<parent />
<child1 />
<child2 />
<child3 />

If you want the "child" elements to be children of "parent" you need to use append.

var $set = $('<div id="parent">0</div>');
$set.append('<div id="child1">1</div>');
$set.append('<div id="child2">2</div>');
$set.append('<div id="child3">3</div>');
$('body').append($set);

which results in

<parent>
    <child1 />
    <child2 />
    <child3 />
</parent>

Upvotes: 5

Related Questions