Reputation: 3716
i have a table and i have two buttons to add and remove rows to this table .
so adding row is easy (i get 3 rows via ajax every time) .
now i want to be able to remove last 3 rows of table by clicking on remove button so unless there is some kind of function or .... to remove recent additions to my table ! i need to remove last three rows of table myself
something like
$('#tbl tr:lt(3)').remove();
but last 3 not first ones !
or i have to do something stupid like
function remove(){
var i ;
for(i=0 ; i < 3 ; i++ ){
$('#table tr:last').remove();
}
alert('removed');
}
Upvotes: 4
Views: 4619
Reputation: 147363
Just to compare with plain JS,
function removeLastRows(table, n) {
if (!table || !n) return;
var row, rows = table.rows;
while (n--) {
row = rows[rows.length];
row.parentNode.removeChild(row);
}
}
removeLastRows(document.getElementById('table', 3));
Upvotes: 0
Reputation: 30103
I agree, it's not stupid. But if I were you, I will add a parameter, the number of rows to remove:
function removeLastRows(numberOfRows){
var i ;
for(i=0 ; i < numberOfRows ; i++ ){
$('#table tr:last').remove();
}
alert('removed');
}
Upvotes: 0
Reputation: 50976
It's not so stupid, it's a nice workaround. To clean it up, I'd use
function remove(){
$('#table tr:last').remove();
$('#table tr:last').remove();
$('#table tr:last').remove();
alert('removed');
}
Upvotes: 2