JQuery table column deleted

I have a table and cannot change the markup:

<table>
    <thead>
        <tr>
            <th>
                blablabla
            </th>
            <th>
                blablabla
            </th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                efgd
            </td>
            <td>
                efghdh
            </td>
        </tr>
    </tbody>
</table>

Here is my function that should remove a column. It is called by clicking on the cell:

function (menuItem, menu) {
    var colnum = $(this).prevAll("td").length;

    $(this).closest('table').find('thead tr th:eq('+colnum+')').remove();
    $(this).closest("table").find('tbody tr td:eq('+colnum+')').remove();    
    return;
}

But it deletes something else, not the column that I would like to delete. Where am I mistaken?

+5
source share
5 answers

The column is largely relevant only to cells, so you need to manually scroll through all the rows and delete the cell by index.

This should give you a good starting point for removing the third column:

$("tr").each(function() {
    $(this).filter("td:eq(2)").remove();
});
+12
source

Used .delegate()for the handler and a more proprietary approach using cellIndexto get the index of the cell that was clicked, and cellsto pull out the cell from each row.

: http://jsfiddle.net/zZDKg/1/

$('table').delegate('td,th', 'click', function() {
    var index = this.cellIndex;
    $(this).closest('table').find('tr').each(function() {
        this.removeChild(this.cells[ index ]);
    });
});
+7

This works fine for me:

$(".tableClassName tbody tr").each(function() {
    $(this).find("td:eq(3)").remove();
});
+5
source

If you have static html (consider a table with 10 columns)

then remove the first column along with the header using below:

 $('#table th:nth-child(1),#table td:nth-child(1)').remove();

now the new table will have 9 columns, now you can delete any column using a number:

 $('#table th:nth-child(7),#table td:nth-child(7)').remove();
+1
source

Remove the first column from each row.

$('.mytable').find("tr td:nth-child(1)").each(function(){
    $(this).remove()
});
0
source

All Articles