Embi Wilde
Embi Wilde

Reputation: 25

append to unordered list (ul) in jquery

<ul id="list">
<li><input name="int[]" type="checkbox" value="1" id="int1" />int1</li>
<li><input name="int[]" type="checkbox" value="2" id="int2" />int2</li>
<li><input name="int[]" type="checkbox" value="3" id="int3" />int3</li>
<li><input name="int[]" type="checkbox" value="4" id="int4" />int4</li>
</ul> 

this

$("#list").append('<li><input name="int[]" type="checkbox" value="55" id="int55" />int55</li>');

make:

<ul id="list">
<li><input name="int[]" type="checkbox" value="1" id="int1" />int1</li>
<li><input name="int[]" type="checkbox" value="2" id="int2" />int2</li>
<li><input name="int[]" type="checkbox" value="3" id="int3" />int3</li>
<li><input name="int[]" type="checkbox" value="4" id="int4" />int4</li>
<li><input name="int[]" type="checkbox" value="55" id="int55" />int55</li>
</ul> 

how can i make for example

<ul id="list">
<li><input name="int[]" type="checkbox" value="1" id="int1" />int1</li>
<li><input name="int[]" type="checkbox" value="2" id="int2" />int2</li>
<li><input name="int[]" type="checkbox" value="55" id="int55" />int55</li>
<li><input name="int[]" type="checkbox" value="3" id="int3" />int3</li>
<li><input name="int[]" type="checkbox" value="4" id="int4" />int4</li>
</ul> 

or

<ul id="list">
<li><input name="int[]" type="checkbox" value="1" id="int1" />int1</li>
<li><input name="int[]" type="checkbox" value="2" id="int2" />int2</li>
<li><input name="int[]" type="checkbox" value="3" id="int3" />int3</li>
<li><input name="int[]" type="checkbox" value="55" id="int55" />int55</li>
<li><input name="int[]" type="checkbox" value="4" id="int4" />int4</li>
</ul> 

?

Upvotes: 2

Views: 1680

Answers (5)

James Allardice
James Allardice

Reputation: 165971

$("#int2").parent().after('<li><input name="int[]" type="checkbox" value="55" id="int55" />int55</li>');

This inserts the new element after the parent of the element with id "int2". See it working here.

You need to use parent because otherwise the new element will be inserted inside the same li element as the input with the given id (although your question title is (now was) misleading... in your examples you want the new element added as a new li, but your title says "append to li".)

Upvotes: 2

Fedor Skrynnikov
Fedor Skrynnikov

Reputation: 5609

Selectors in jquery are realy powerful

 $("#list > li:eq(2)").after('<li><input name="int[]" type="checkbox" value="55" id="int55" />int55</li>');

Upvotes: 1

vinceh
vinceh

Reputation: 3510

A combination of .eq() and .after() will suffice. Look :)

Upvotes: 0

FishBasketGordo
FishBasketGordo

Reputation: 23142

If I understand your question, you'll want to do something like this:

var pos = 2; // Will insert before the second <li>
$('#list :nth-child(' + pos + ')').before('<li>NEW</li>');

Upvotes: 0

a&#39;r
a&#39;r

Reputation: 36999

You can use the after() method. eg.

$('li').eq(2).after('...')

Upvotes: 0

Related Questions