jQuery delete all table rows except first

后端 未结 14 1178
失恋的感觉
失恋的感觉 2021-01-29 17:40

Using jQuery, how do I delete all rows in a table except the first? This is my first attempt at using index selectors. If I understand the examples correctly, the following sh

相关标签:
14条回答
  • 2021-01-29 18:16

    Another way to accomplish this is using the empty() function of jQuery with the thead and tbody elements in your table.

    Example of a table:

    <table id="tableId">
    <thead>
        <tr><th>Col1</th><th>Col2</th></tr>
    </thead>
    <tbody>
        <tr><td>some</td><td>content</td></tr>
        <tr><td>to be</td><td>removed</td></tr>
    </tbody>
    </table>
    

    And the jQuery command:

    $("#tableId > tbody").empty();
    

    This will remove every rows contained in the tbody element of your table and keep the thead element where your header should be. It can be useful when you want to refresh only the content of a table.

    0 讨论(0)
  • 2021-01-29 18:18
    
    $("#p-items").find( 'tr.row-items' ).remove();
    
    0 讨论(0)
  • 2021-01-29 18:21

    To Remove all rows, except the first one (except header), use the below code:

    $("#dataTable tr:gt(1)").remove();

    0 讨论(0)
  • 2021-01-29 18:21

    This works perfectly

    $("#myTable tbody").children( 'tr:not(:first)' ).html("");
    
    0 讨论(0)
  • 2021-01-29 18:22
    $('#table tr').slice(1).remove();
    

    I remember coming across that 'slice' is faster than all other approaches, so just putting it here.

    0 讨论(0)
  • 2021-01-29 18:23

    If it were me, I'd probably boil it down to a single selector:

    $('someTableSelector tr:not(:first)').remove();
    
    0 讨论(0)
提交回复
热议问题