开发者

jQuery: append next to last?

Here's my HTML:

<ol>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ol>

Then I append a new item with this: $('ol').append('<li>New item</li>');

But, what I want to do, is append that new before the last item. So in this example, the new list item would be placed between the second a开发者_如何学Pythonnd third. The number of items in the list could be as few as 2 or as many as hundreds, but it should always insert before the next to last item.


For that, you have to select the last list item and then tell jQuery to add the new one before the one selected:

$('ol li:last').before('<li>New item</li>');


This should do the trick

$('ol li:last').before('<li>New item</li>');

Example on jsfiddle


$('ol').last().prev().append('<li>New item</li>');

should work I believe.

Or indeed, what the person above & below me said looks a bit neater :)


I had trouble with this when the last list item had a special class. I needed to do this:

<ul id="my_ul">
   <li>One</li>
   <li>Two</li>
   <li class="last_class">Always Last</li>
</ul>

$('#my_ul li.last_class').before('<li>New Item</li>');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜