最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add LI in UL in arbitrary position using jQuery - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 9

You 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>');
发布评论

评论列表(0)

  1. 暂无评论