Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove all class divs except the last 2 using jquery?

How do I remove all class divs except the last 2 using jquery?

I have a set of comments that show in a .comment_container class. When show all comments is clicked a list of all comments for a particular micropost is shown before the most 2 recent which show by default.

How ever if a user types a comment before clicking to see all comments this comment is added to the list and now 3 recent comments show. Because of the way I've set up some back end code it causes the least most recent comment to be shown twice when the show all link is clicked.

No need to get into the details but what I've decided to do is count the total divs and from the total remove all the divs but 2 (the last 2 in the list which are the most recent).

How can I achieve this using jquery?

Kind regards

like image 763
LondonGuy Avatar asked Apr 18 '12 12:04

LondonGuy


1 Answers

Use slice() (and credit to @Felix Kling for the update):

$(".comment_container").slice(0, -2).remove();

However, given your description of your problem this doesn't sound like the best course of action. It may be worth you starting a new question about the problem you have with the comments with some detail about your code.

More info on slice().

like image 93
Rory McCrossan Avatar answered Nov 14 '22 04:11

Rory McCrossan