1

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++;
});      

4 Answers 4

10

Try the following:

if ($("table tr").length != 1) {
     $("table tr:last").remove();
}
1
  • 1
    all great answers.. wish i could accept them all :) (they should probably add that feature!)
    – Zabs
    Jul 25, 2012 at 16:07
2

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();
2

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();
1

Try:

$("#remove").click(function(event) {
    event.preventDefault();        
    $("table tr:not(':first')").remove();
    i++;
});

Demo here: http://jsfiddle.net/aGukb/

6
  • omg.. so simple & elegent - brilliant stuff Ayman thanks for that!
    – Zabs
    Jul 25, 2012 at 16:01
  • I meant ":first" by the way! Jul 25, 2012 at 16:02
  • 1
    @Zabs: You've commented that two different answers work for you, but the two answers do different things. What do you actually want to do?
    – user1106925
    Jul 25, 2012 at 16:06
  • both do the same thing but the raminson effort looks the simpler one even though Ayman's one is less code. Either way thanks :-) Sorry @amnotiam you was right i am sorry
    – Zabs
    Jul 25, 2012 at 16:08
  • 1
    Sorry.. i meant to say... the first effort by Raminson is the one I am trying to acheive :) Long day!
    – Zabs
    Jul 25, 2012 at 16:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.