Friday, May 1, 2009

Remove the bottom table row using jQuery

I have posted a small jQuery code a while ago which adds a table row at the bottom of any given table. The code takes into the consideration tbody tag and also can be used as a jQuery plugin.

Recently I was asked to write a jQuery or JavaScript code that removes the last/bottom row from the given table. The jQuery code I wrote was surprisingly small.

jQuery code to remove bottom/last table row

// Simple bottom row removal $('#myTable tr:last').remove(); // Removing n'th (ex. 3rd) row from the table $('#myTable tr:eq(2)').remove();

Improved jQuery code

We can improve our simple bottom row removal code to take into the consideration the possible <tbody> and <tfoot> HTML tags that can be found in tables.

// Improved code that takes into the consideration // the <tbody> tag $('#myTable').each(function(){ if($('tbody', this).length > 0){ $('tbody tr:last', this).remove(); }else { $('tr:last', this).remove(); } }); // Improved code that for n'th row removal // In this example we are removing 3rd row $('#myTable').each(function(){ if($('tbody', this).length > 0){ $('tbody tr:eq(2)', this).remove(); }else { $('tr:eq(2)', this).remove(); } });

Bonus JavaScript function

You can also turn the code above into the jQuery plugin or JavaScript function. Here is a JavaScript function to remove the bottom table row (you can amend the code to make it remove n’th row).

/* Remove the last/bottom table row */ function removeTableRow(jQtable){ jQtable.each(function(){ if($('tbody', this).length > 0){ $('tbody tr:last', this).remove(); }else { $('tr:last', this).remove(); } }); } // Here is how to use it removeTableRow($('table'));
Also the above javascript function can easily be rewritten as a jQuery plugin. Read this post to learn how to create jQuery plugins.

3 comments:

  1. For some reason .length is always returning 1, so this doesnt work for me.

    Any ideas?

    ReplyDelete
  2. You mean in:

    if($('tbody', this).length > 0){

    This means your table HTML markup has <tbody> in it...

    ReplyDelete
  3. All the content in my second column shift to the right when I hide the last row in my table, any suggestions?

    ReplyDelete