neo
neo

Reputation: 2471

JQuery remove selected rows from a table

Suppose I have a table:

 <table id="mytable">
    <tr>1</tr>
    <tr>2</tr>
    <tr>3</tr>
    <tr>4</tr>
    <tr>5</tr>
    <tr>6</tr>
    ...
    ...
   </table>

I know you can use ('#mytable').find("tr:gt(n)").remove(); to remove all rows after nth row. But is there a similar function to let you specify a range of rows you want to remove? say I want to remove row 2 to row 5? or I just want to remove row 2?

do i have to add an id to each row to achieve this?

thanks

Upvotes: 2

Views: 4883

Answers (5)

tijs
tijs

Reputation: 566

you can try to use :eq() selector:

$("#mytable").find("tr:eq(index)").remove();

And to delete a range of rows you can use that selector and just loop through them

Upvotes: 0

Danil Speransky
Danil Speransky

Reputation: 30453

Try function for filter it:

var rangeFunction = function(index){
  return index >=2 && index <=5;
};

$('#mytable').filter(rangeFunction).remove();

It is the common method. If you want just simple linear range, then try:

$("#mytable tr").slice(2, 4).remove();

Upvotes: 0

epascarello
epascarello

Reputation: 207501

You can use jQuery slice(start,[end]) for a range and eq(index) for single rows.

var myRows = $("table tr").slice(1,5);

Upvotes: 4

Chris Pratt
Chris Pratt

Reputation: 239260

$('#mytable').find('tr').filter(function(index){
    return index >=2 && index <=5;
}).remove();

Upvotes: 0

Snow Blind
Snow Blind

Reputation: 1164

Would this be OK?

$('#mytable tr:gt(2):lt(5)').remove();

Upvotes: 0

Related Questions