How to remove all divs of a class except the last 2 using jquery?

How to remove all divs of a class except the last 2 using jquery?

I have a set of comments that appear in the .comment_container class. When all comments are displayed, a list of all comments for a particular micro-post is displayed until the very last 2, which are displayed by default.

Anyway, if the user enters a comment before clicking to see all the comments, that comment is added to the list and the last 3 comments now appear. Due to the way I configured some kind of end-of-code code, it invokes the last two last comments when a click on the entire link is displayed.

No need to go into details, but what I decided to do was to calculate the total divs and from completely removing all divs, but 2 (the last 2 in the list, which are the very last ones). A.

How can I achieve this with jquery?

Yours faithfully

+5
source share
2 answers

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

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

However, given your description of your problem, this does not seem to be the best course of action. It might be worth starting a new question about the comment problem with some details about your code.

Additional information about slice () .

+7
source

Do you have the last two divs in which you do not want to include identifiers?

, jQuery .not(), div , , -

$('.comment_container').not('#lastDiv, #lastButone')

, 2.

. not()

0

All Articles