Reputation: 43
This is the code for removing all except first row using jQuery:
$("#tblCustomers").find("tr:not(:first)").remove();
How can I remove all but the first two rows?
Upvotes: 2
Views: 4160
Reputation: 4321
use filter method
$("#tblCustomers tr").filter(function(){
return $(this).index() > 2;
}).remove();
Upvotes: 2
Reputation: 5176
May I propose a plain javascript sollution? Itterates the rows backwords and removes them when the counter is greater than 2.
var table = document.getElementById("myTable");
for (var i = table.rows.length; i>0 ; i--) { //iterate through rows
if(i>2) {
row = table.rows[i-1];
row.parentNode.removeChild(row);
}
}
<table id="myTable">
<tr>
<td>1</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>2</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>3</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>4</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
</table>
Upvotes: 0
Reputation: 67505
You could use the both selectors :not
and :nth-child
like :
$('#tblCustomers tr:not(:nth-child(-n+2))').remove();
Hope this helps.
$('#tblCustomers tr:not(:nth-child(-n+2))').remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tblCustomers">
<tr><td>0</td></tr>
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
</table>
Upvotes: 4
Reputation: 93561
$("#tblCustomers tr").filter(function(index){
return index >= 2;
}).remove();
The first parameter to a filter is the index position. Return true for the rows you want to delete
Upvotes: 2
Reputation: 337560
You can use :gt()
to find rows with an index greater than that specified. Try this:
$("#tblCustomers tr:gt(1)").remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tblCustomers">
<tr><td>0</td></tr>
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
</table>
Note that indexes are zero-based, so index 1 is the second row.
Alternatively you could slice()
the elements within the selector:
$("#tblCustomers tr").slice(2).remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tblCustomers">
<tr><td>0</td></tr>
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
</table>
Upvotes: 15