tags:

views:

96

answers:

3

I am prepending a li to a ul every few seconds. I want to set the limit to 20 items. Once there are 20 items I want to remove the oldest item so that there is never more than 20 items. How can I do this in JQuery?

+2  A: 

To remove the last child do:

$('li:last-child').remove();

To remove the 20th child do (0 indexed)

$('li:eq(19)').remove();
PetersenDidIt
+1 To be safe in case you have multiple `ul`, use a more specific selector. E.g.: `$('#theUL li:eq(19)')`
o.k.w
+7  A: 

You can use the gt selector to select everything after a specific element or the lt for anything before. You'd have to use the length attribute of the array if you'll need to find out the existing length.

EG:

$('#ulID li:gt(19)').remove()

You can also use :first and :last if you're never inserting more than 1 item at a time.

Tim Schneider
This will leave 21 items in the list. Use `gt(19)` since it is a zero based index.
Doug Neiner
Good point, I've updated my post to say 19.
Tim Schneider
Cool, already gave you a +1 for a great answer :)
Doug Neiner
A: 

After you prepend do the following...

//Assuming $ul = a jquery object that contains your ul element.
//If there are more than 20 items, remove oldest item
if ($ul.children().size() > 20) {
    $ul.children(":last-child").remove();
}

or if you have the li elements in a jquery object already, you can also do the following

if ($li.size() > 20) {
    $li.find(":last-child").remove();
}
MillsJROSS