Search code examples
jqueryhtml-tableclone

jQuery clone second last row and insert at the end of table


I'm making some code to dynamically add more rows to a table on click. I want to clone the last two rows of my table and then append them at the end. Of course, the table is dynamic so there is not a fixed number of rows. I have got the last row cloning okay but I can't get the second last row. How would I select it?

$('.additional_row').live('click', function() {
    var $rows = $('#maintable tr'); 
var $secondLastRow = $rows[$rows.length - 2]; 

$('#maintable tbody>tr:nth-child(' + $secondLastRow + ')').clone(true).insertAfter('#maintable tbody>tr:last');
$('#maintable tbody>tr:last').clone(true).insertAfter('#maintable tbody>tr:last');

return false;
});

Solution

  • $('#maintable tbody>tr:last').prev('tr') will give you the second last one