jQuery delete / remove table row tr on Button Click

/ / 5 Comments

jQuery remove table row on button click: This article explains how to remove selected table row .i.e how to delete table row by id or class-name on button click event in jQuery. On button click, we remove the selected table row (tr tag ) maybe it's dynamically added table row or already available on DOM.

Using the jQuery .on() method will be able to select dynamically added elements by specifying their class-name or Id and then using the jQuery .remove() method removes the table row.

The below gif shows the demo of our working code. Where on delete button click, that rows get deleted.

Output :

Video:


Step to Delete Table Row in jQuery:

  • Add HTML table with some data
  • Use jQuery .remove() method

HTML: Add HTML table with some data ( to delete table row)

First, we have to add a table tag in our HTML page with some tr table row and td table data and a button with text as Delete. Here delete button is used to delete a specific table row.

Our HTML structure looks as shown in the below-written code.

//*
<table id="tbUser">
    <tr>
        <th>Sr</th><th>Name</th><th>Location</th><th></th>
    </tr>
    <tr>
        <td>1</td><td>Amit</td><td>Ghatkopar</td>
        <td><button class="btnDelete">Delete</button></td>
    </tr>
    <tr>
        <td>2</td><td>Vicky</td><td>Powai</td>
        <td><button class="btnDelete">Delete</button></td>
    </tr>
     .......... // so on data
</table>
//*
In the above table, we have added some data and in each row, we have a button with a common class as “btnDelete”. Now next will add a click event on the button click and on clicking it, will delete that row tr from our HTML table.

jQuery: Code to Remove Table Row (tr) on Button Click

Here, we make a jQuery click event on the button tag.  Using the closest() method we select the current row ie closest tr of our delete button, and then with the remove() method will delete that record. 

Similarly for deleting the next row tr we use .next() method along with .remove() this will delete the next table row. This is how we were able to delete the table row our final code looks like as written below.

//*
$("#tbUser").on('click', '.btnDelete', function () {
    $(this).closest('tr').remove();
});
//*

View Demo

So finally we were able to delete the table row on the button click in jQuery. If you want to read or access table cell content TD value then pls check this Complete Tutorial  4 ways to get table cell td value.

Other Reference:

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

5 Comments