I want to add LI in my existing UL. My HTML is like this:
<ul id="friends">
<li><a href="javascript:void(0);" class="new">Friend 2</a></li>
<li><a href="javascript:void(0);" class="new">Friend 3</a></li>
<li><a href="javascript:void(0);" class="new">Friend 4</a></li>
<li><a href="javascript:void(0);" class="offline">Friend 6</a></li>
<li><a href="javascript:void(0);" class="offline">Friend 7</a></li>
<li><a href="javascript:void(0);" class="invited">Friend 8</a></li>
</ul>
i know i can use it to add LI at the and
$("#friends").append('<li><a href="javascript:void(0);" class="new">Friend 1</a></li>');
But it will add in last position and i want to add it at first position or in middle. How to specify the position at which I want to insert the LI?
I want to add LI in my existing UL. My HTML is like this:
<ul id="friends">
<li><a href="javascript:void(0);" class="new">Friend 2</a></li>
<li><a href="javascript:void(0);" class="new">Friend 3</a></li>
<li><a href="javascript:void(0);" class="new">Friend 4</a></li>
<li><a href="javascript:void(0);" class="offline">Friend 6</a></li>
<li><a href="javascript:void(0);" class="offline">Friend 7</a></li>
<li><a href="javascript:void(0);" class="invited">Friend 8</a></li>
</ul>
i know i can use it to add LI at the and
$("#friends").append('<li><a href="javascript:void(0);" class="new">Friend 1</a></li>');
But it will add in last position and i want to add it at first position or in middle. How to specify the position at which I want to insert the LI?
Share Improve this question edited Apr 2, 2013 at 8:07 Cjxcz Odjcayrwl 22.9k43 gold badges149 silver badges230 bronze badges asked Apr 1, 2013 at 18:15 KabirKabir 2,1765 gold badges21 silver badges24 bronze badges 1- 3 api.jquery./prepend and api.jquery./after -- just browse the docs until you find the most useful method for your purposes. – Blazemonger Commented Apr 1, 2013 at 18:15
2 Answers
Reset to default 9You have to use prepend() instead of append
$("#friends").prepend('<li><a href="javascript:void(0);" class="new">Friend 1</a></li>');
To append at particular position you can use eq()
$("#friends li").eq(4).append('<li><a href="javascript:void(0);" class="new">Friend 1</a></li>');
Try prepend.
$("#friends").prepend('<li><a href="javascript:void(0);" class="new">Friend 1</a></li>');