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.