简体   繁体   中英

How to delete the last column in an HTML TABLE using by jquery?

I have an HTML TABLE:

<table id="persons" border="1">
    <thead id="theadID">
        <tr>
            <th>Name</th>
            <th>sex</th>
            <th>Message</th>
        </tr>
    </thead>
    <tbody id="tbodyID">
        <tr>
            <td>Viktor</td>
            <td>Male</td>
            <td>etc</td>
        </tr>
        <tr>
            <td>Melissa</td>
            <td>Female</td>
            <td>etc</td>
        </tr>
        <tr>
            <td>Joe</td>
            <td>Male</td>
            <td>etc</td>
        </tr>
    </tbody>
</table>
<input type="button" onclick="deleteLastColumn();" value="do it"/>

I need a javascript/jquery code, which delete the last column (message) in the table:

function deleteLastColumn() {
    $("#theadID tr th:not(:last-child)......
    $("#tbodyID tr td:not(:last-child)......
}

So the result should be this:

<table id="persons" border="1">
    <thead id="theadID">
        <tr>
            <th>Name</th>
            <th>sex</th>
        </tr>
    </thead>
    <tbody id="tbodyID">
        <tr>
            <td>Viktor</td>
            <td>Male</td>
        </tr>
        <tr>
            <td>Melissa</td>
            <td>Female</td>
        </tr>
        <tr>
            <td>Joe</td>
            <td>Male</td>
        </tr>
    </tbody>
</table>

I know there is the ":not(last)" method, but I can't find any example to my problem. Could anyone help me?

Try

$('#persons tr').find('th:last-child, td:last-child').remove()

Demo: Fiddle

You can use this solution to achieve it easily..

 function myFunction() { var allRows = document.getElementById('my_table').rows; for (var i=0; i< allRows.length; i++) { allRows[i].deleteCell(-1); } } 
 <!DOCTYPE html> <html> <head> </head> <body> <table id="my_table"> <thead > <th>Column 1</td> <th>Column 2</td> <th>Column 3</td> </thead > <tr > <td>Number 1</td> <td>String 1</td> <td>Decimal 1</td> </tr> <tr > <td>Number 2</td> <td>String 2</td> <td>Decimal 2</td> </tr> <tr > <td>Number 3</td> <td>String 3</td> <td>Decimal 3</td> </tr> </table><br> <button onclick="myFunction()">Remove Last Column</button> </body> </html> 

In addition to Arun P Johny's answer,

That would let you remove last row each time you click the button. If you just want to remove one column, not others you may try this.

function deleteLastColumn() {
    $(document).find('.last').remove()
}

after adding class last to the last td and th of the table.

Demo : Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM