jQuery Add Remove Row in Table & Clear Table

In this article, I’m going to show how to add remove row in table and how to clear table body. Let’s get started:

Table of Contents

  1. Take a Table
  2. Add Row
  3. Add Row From Foreach Loop
  4. Remove Row
  5. Clear Table

Take a Table

Let’s take a table:

<table id="myTable">
  <tbody>
    <tr><td>Foo 1</td></tr>
    <tr><td>Foo 2</td></tr>
  </tbody>
</table>

Add Row

We can add row to myTable in some ways. Let’s have a look at some methods:

// method 1
$('#myTable').append('<tr><td>New row</td></tr>');

// method 2
$("#myTable > tbody").append("<tr><td>New row1</td></tr>");

// method 3:
$("#myTable").last().append("<tr><td>New row</td></tr>");

Add Row From Foreach Loop

We can easily add row from foreach loop:

var data = [1, 2, 3, 4];

$.each(data , function(index, val) {
  $('#myTable').append('' + val + '');
});

Remove Row

Have a look at some ways to remove row from table:

// remove first child
$('#myTable tr:first').remove();

// remove last child
$('#myTable tr:last').remove();

// remove all rows except first row
$("#myTable").find("tr:gt(0)").remove();

Clear Table

// empty table
$("#myTable").empty();

// clear head
$("#myTable  thead").remove();

// clear body
$("#myTable  tbody").remove();
$("#myTable > tbody").html("");

That’s it. Thanks for reading.