Reputation: 14142
I am using jQuery to remove table rows - my script works ok but I don't want the button to be able to remove the very first table row. Can anyone suggest how this is done?
$("#remove").click(function(event) {
event.preventDefault();
$("table tr:last").remove();
i++;
});
Upvotes: 1
Views: 8410
Reputation: 8767
You can use gt()
and not()
:
$('table').find('tr:gt(0):last').remove();
This finds all rows with an index greater than 0, gt(0)
and selects the last row, :last
and then removes that element.
Demo: http://jsfiddle.net/XhtC8/
If you wanted to remove all rows but the first then you can remove :last
:
$('table').find('tr:gt(0)').remove();
Upvotes: 2
Reputation: 664395
How about
$("tr:last:not(:first)").remove();
You don't need the table
selector as all rows are inside tables, but it might be useful to specify the table element from which you want to remove (avoiding side effects if you later would add other tables).
Example: Remove all rows from $table
except the first:
$("tr:not(:first)", $table).remove();
Upvotes: 2
Reputation: 11552
Try:
$("#remove").click(function(event) {
event.preventDefault();
$("table tr:not(':first')").remove();
i++;
});
Demo here: http://jsfiddle.net/aGukb/
Upvotes: 1
Reputation: 144679
Try the following:
if ($("table tr").length != 1) {
$("table tr:last").remove();
}
Upvotes: 10