CastleDweller
CastleDweller

Reputation: 8364

jQuery remove last table column

I currently have a table that can be N columns and N rows. In the interface I have a button to remove the last column, but I can't figure out how to remove the last td from all the rows, what I've achieved so far is to remove the first row tdand the last row td, but leave the others there.

Here is my code (only deletes the last title currently):

function removeTableColumn() {
    /*
        removeTableColumn() - Deletes the last column (all the last TDs).
    */
    $('#tableID thead tr th:last').remove(); // Deletes the last title
    $('#tableID tbody tr').each(function() {
        $(this).remove('td:last'); // Should delete the last td for each row, but it doesn't work
    });
}

Am I missing something?

Upvotes: 19

Views: 35317

Answers (3)

dnxit
dnxit

Reputation: 7350

You can remove any column from a table like this

    //remove the 1st column
     $('#table').find('td,th').first().remove();

    //remove the 1st column
    $('table tr').find('td:eq(1),th:eq(1)').remove();

   //remove the 2nd column
   $('table tr').find('td:eq(1),th:eq(1)').remove();

   //remove the nth column
   $('table tr').find('td:eq(n),th:eq(n)').remove();

for reference

Upvotes: 1

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262929

That's because the :last selector only matches the last element in the set.

You might be looking for :last-child, which matches the elements that are the last child of their parent:

$("#tableID th:last-child, #tableID td:last-child").remove();

Upvotes: 39

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99909

:last returns the last element found by the selector. So #tableID tr td:last would return only one td.

You can select the last td of each tr be doing this:

$('#tableID tr').find('th:last, td:last').remove();

Upvotes: 8

Related Questions