-1

I have an html which, of course, have a table element, and in the tbody, I have a button that will delete rows of the table.

I have assigned an onclick="" function to the button. (Function here)

How to delete only the rows on the body of the table (tbody), and not the row in the head of the table (thead) ?

FIDDLE HERE

Lloyd Dominic
  • 778
  • 8
  • 25

1 Answers1

1

Wrap body rows to tbody element and than you can to select only table tbody tr to be removed. With jQuery you can do $('table tbody tr').remove();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
  <thead>
    <tr>
      <th>Name</th>
      <th>Action</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Some content</td>
      <td>
        <button onClick="$(this).closest('tr').remove()">Remove</button>
      </td>
    </tr>

    <tr>
      <td>Some content</td>
      <td>
        <button onClick="$(this).closest('tr').remove()">Remove</button>
      </td>
    </tr>

    <tr>
      <td>Some content</td>
      <td>
        <button onClick="$(this).closest('tr').remove()">Remove</button>
      </td>
    </tr>

    <tr>
      <td>Some content</td>
      <td>
        <button onClick="$(this).closest('tr').remove()">Remove</button>
      </td>
    </tr>
  </tbody>
</table>
<button onClick="$('#table tbody tr').remove()">Remove all rows</button>
Justinas
  • 41,402
  • 5
  • 66
  • 96