Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all rows from a table except first two and last?

I've seen a lot of questions about how to select all but the first and last rows of a table, but I want to know how to select everything except the first TWO rows and the last. Right now I have this to select all but the first two:

$("#sometable").find("tr:gt(1)").remove();

and I need some way to get the last one as well. Maybe some way to combine with

:not(:last)

?

I'm fairly new to jQuery and any help would be appreciated.

like image 406
cnhe Avatar asked Jul 05 '12 18:07

cnhe


People also ask

How we can delete all table rows except first one using jQuery?

The jQuery function removes all the rows except the first one using the remove() method. Syntax: $('#btn').

How to remove all rows of table in jQuery?

The jQuery remove() method is used to remove a row from HTML table. jQuery remove() Method: This method removes the selected elements alongwith text and child nodes. This method also removes data and events of the selected elements.


2 Answers

This is what you need:

$("#sometable").find('tr').slice(2,-1).remove()

DEMO

jsperf of my and @Evan's solutions.

enter image description here

like image 194
Engineer Avatar answered Sep 28 '22 18:09

Engineer


Just combine the selectors:

$("#sometable").find("tr:gt(1):not(:last)").remove();

JSFiddle

like image 26
Evan Mulawski Avatar answered Sep 28 '22 18:09

Evan Mulawski