jQuery Add Remove Row in Table & Clear Table

Published on June 24, 2021 56 sec read

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">
    <tr><td>Foo 1</td></tr>
    <tr><td>Foo 2</td></tr>

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

Clear Table

// empty table

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

// clear body
$("#myTable  tbody").remove();
$("#myTable > tbody").html("");
That’s it. Thanks for reading. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.

Hey, I'm Md Obydullah. I build open-source projects and write article on Laravel, Linux server, modern JavaScript and more on web development.