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">
    <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.

Software Engineer | Ethical Hacker & Cybersecurity...

Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.