[javascript] What is the best way to remove a table row with jQuery?

What is the best method for removing a table row with jQuery?

This question is related to javascript jquery html-table

The answer is


$('#myTable tr').click(function(){
    $(this).remove();
    return false;
});

Even a better one

$("#MyTable").on("click", "#DeleteButton", function() {
   $(this).closest("tr").remove();
});

if you have HTML like this

<tr>
 <td><span class="spanUser" userid="123"></span></td>
 <td><span class="spanUser" userid="123"></span></td>
</tr>

where userid="123" is a custom attribute that you can populate dynamically when you build the table,

you can use something like

  $(".spanUser").live("click", function () {

        var span = $(this);   
        var userid = $(this).attr('userid');

        var currentURL = window.location.protocol + '//' + window.location.host;
        var url = currentURL + "/Account/DeleteUser/" + userid;

        $.post(url, function (data) {
          if (data) {
                   var tdTAG = span.parent(); // GET PARENT OF SPAN TAG
                   var trTAG = tdTAG.parent(); // GET PARENT OF TD TAG
                   trTAG.remove(); // DELETE TR TAG == DELETE AN ENTIRE TABLE ROW 
             } else {
                alert('Sorry, there is some error.');
            }
        }); 

     });

So in that case you don't know the class or id of the TR tag but anyway you are able to delete it.


The easiest method to remove rows from table:

  1. Remove row of table using its unique ID.
  2. Remove based on the order/index of that row. Ex: remove the third or fifth row.

For example:

 <table id='myTable' border='1'>
    <tr id='tr1'><td>Row1</td></tr>
    <tr id='tr2'><td>Row2</td></tr>
    <tr id='tr3'><td>Row3</td></tr>
    <tr id='tr4'><td>Row4</td></tr>
    <tr id='tr5'><td>Row5</td></tr>
  </table>

//======REMOVE TABLE ROW=========
//1. remove spesific row using its ID
$('#tr1').remove();

//2. remove spesific row using its order or index.
//row index started from 0-n. Row1 index is 0, Row2 index is 1 and so on.
$('#myTable').find('tr:eq(2)').remove();//removing Row3

I appreciate this is an old post, but I was looking to do the same, and found the accepted answer didn't work for me. Assuming JQuery has moved on since this was written.

Anyhow, I found the following worked for me:

$('#resultstbl tr[id=nameoftr]').remove();

Not sure if this helps anyone. My example above was part of a larger function so not wrapped it in an event listener.


All you have to do is to remove the table row (<tr>) tag from your table. For example here is the code to remove the last row from the table:

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

*Code above was taken from this jQuery Howto post.


function removeRow(row) {
    $(row).remove();
}

<tr onmousedown="removeRow(this)"><td>Foo</td></tr>

Maybe something like this could work as well? I haven't tried doing something with "this", so I don't know if it works or not.


$('tr').click(function()
 {
  $(this).remove();
 });

i think you will try the above code, as it work, but i don't know why it work for sometime and then the whole table is removed. i am also trying to remove the row by click the row. but could not find exact answer.


function removeRow(row) {
    $(row).remove();
}

<tr onmousedown="removeRow(this)"><td>Foo</td></tr>

Maybe something like this could work as well? I haven't tried doing something with "this", so I don't know if it works or not.


If you are using Bootstrap Tables

add this code snippet to your bootstrap_table.js

BootstrapTable.prototype.removeRow = function (params) {
    if (!params.hasOwnProperty('index')) {
        return;
    }

    var len = this.options.data.length;

    if ((params.index > len) || (params.index < 0)){
        return;
    }

    this.options.data.splice(params.index, 1);

    if (len === this.options.data.length) {
        return;
    }

    this.initSearch();
    this.initPagination();
    this.initBody(true);
};

Then in your var allowedMethods = [

add 'removeRow'

Finally you can use $("#your-table").bootstrapTable('removeRow',{index:1});

Credits to this post


Is the following acceptable:

$('#myTableRow').remove();

Another one by empty() :

$(this).closest('tr').empty();

if you have HTML like this

<tr>
 <td><span class="spanUser" userid="123"></span></td>
 <td><span class="spanUser" userid="123"></span></td>
</tr>

where userid="123" is a custom attribute that you can populate dynamically when you build the table,

you can use something like

  $(".spanUser").live("click", function () {

        var span = $(this);   
        var userid = $(this).attr('userid');

        var currentURL = window.location.protocol + '//' + window.location.host;
        var url = currentURL + "/Account/DeleteUser/" + userid;

        $.post(url, function (data) {
          if (data) {
                   var tdTAG = span.parent(); // GET PARENT OF SPAN TAG
                   var trTAG = tdTAG.parent(); // GET PARENT OF TD TAG
                   trTAG.remove(); // DELETE TR TAG == DELETE AN ENTIRE TABLE ROW 
             } else {
                alert('Sorry, there is some error.');
            }
        }); 

     });

So in that case you don't know the class or id of the TR tag but anyway you are able to delete it.


If the row you want to delete might change you can use this. Just pass this function the row # you wish to delete.

function removeMyRow(docRowCount){
   $('table tr').eq(docRowCount).remove();
}

Easy.. Try this

$("table td img.delete").click(function () {
    $(this).parent().parent().parent().fadeTo(400, 0, function () { 
        $(this).remove();
    });
    return false;
});

If you are using Bootstrap Tables

add this code snippet to your bootstrap_table.js

BootstrapTable.prototype.removeRow = function (params) {
    if (!params.hasOwnProperty('index')) {
        return;
    }

    var len = this.options.data.length;

    if ((params.index > len) || (params.index < 0)){
        return;
    }

    this.options.data.splice(params.index, 1);

    if (len === this.options.data.length) {
        return;
    }

    this.initSearch();
    this.initPagination();
    this.initBody(true);
};

Then in your var allowedMethods = [

add 'removeRow'

Finally you can use $("#your-table").bootstrapTable('removeRow',{index:1});

Credits to this post


You can use:

$($(this).closest("tr"))

for finding the parent table row of an element.

It is more elegant than parent().parent() which is what I started out doing and soon learnt the error of my ways.

--Edit -- Someone pointed out that the question was about removing the row...

$($(this).closest("tr")).remove()

As pointed out below you can simply do:

$(this).closest('tr').remove();

A similar code snippet can be used for many operations such as firing events on multiple elements.


id is not a good selector now. You can define some properties on the rows. And you can use them as selector.

<tr category="petshop" type="fish"><td>little fish</td></tr>
<tr category="petshop" type="dog"><td>little dog</td></tr>
<tr category="toys" type="lego"><td>lego starwars</td></tr>

and you can use a func to select the row like this (ES6):

const rowRemover = (category,type)=>{
   $(`tr[category=${category}][type=${type}]`).remove();
}

rowRemover('petshop','fish');

Is the following acceptable:

$('#myTableRow').remove();

Another one by empty() :

$(this).closest('tr').empty();

You can use:

$($(this).closest("tr"))

for finding the parent table row of an element.

It is more elegant than parent().parent() which is what I started out doing and soon learnt the error of my ways.

--Edit -- Someone pointed out that the question was about removing the row...

$($(this).closest("tr")).remove()

As pointed out below you can simply do:

$(this).closest('tr').remove();

A similar code snippet can be used for many operations such as firing events on multiple elements.


The easiest method to remove rows from table:

  1. Remove row of table using its unique ID.
  2. Remove based on the order/index of that row. Ex: remove the third or fifth row.

For example:

 <table id='myTable' border='1'>
    <tr id='tr1'><td>Row1</td></tr>
    <tr id='tr2'><td>Row2</td></tr>
    <tr id='tr3'><td>Row3</td></tr>
    <tr id='tr4'><td>Row4</td></tr>
    <tr id='tr5'><td>Row5</td></tr>
  </table>

//======REMOVE TABLE ROW=========
//1. remove spesific row using its ID
$('#tr1').remove();

//2. remove spesific row using its order or index.
//row index started from 0-n. Row1 index is 0, Row2 index is 1 and so on.
$('#myTable').find('tr:eq(2)').remove();//removing Row3

id is not a good selector now. You can define some properties on the rows. And you can use them as selector.

<tr category="petshop" type="fish"><td>little fish</td></tr>
<tr category="petshop" type="dog"><td>little dog</td></tr>
<tr category="toys" type="lego"><td>lego starwars</td></tr>

and you can use a func to select the row like this (ES6):

const rowRemover = (category,type)=>{
   $(`tr[category=${category}][type=${type}]`).remove();
}

rowRemover('petshop','fish');

Easy.. Try this

$("table td img.delete").click(function () {
    $(this).parent().parent().parent().fadeTo(400, 0, function () { 
        $(this).remove();
    });
    return false;
});

All you have to do is to remove the table row (<tr>) tag from your table. For example here is the code to remove the last row from the table:

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

*Code above was taken from this jQuery Howto post.


If the row you want to delete might change you can use this. Just pass this function the row # you wish to delete.

function removeMyRow(docRowCount){
   $('table tr').eq(docRowCount).remove();
}

Is the following acceptable:

$('#myTableRow').remove();

I appreciate this is an old post, but I was looking to do the same, and found the accepted answer didn't work for me. Assuming JQuery has moved on since this was written.

Anyhow, I found the following worked for me:

$('#resultstbl tr[id=nameoftr]').remove();

Not sure if this helps anyone. My example above was part of a larger function so not wrapped it in an event listener.


function removeRow(row) {
    $(row).remove();
}

<tr onmousedown="removeRow(this)"><td>Foo</td></tr>

Maybe something like this could work as well? I haven't tried doing something with "this", so I don't know if it works or not.


try this for size

$(this).parents('tr').first().remove();

full listing:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
        $('.deleteRowButton').click(DeleteRow);
      });

    function DeleteRow()
    {
      $(this).parents('tr').first().remove();
    }
  </script>
</head>
<body>
  <table>
    <tr><td>foo</td>
     <td><a class="deleteRowButton">delete row</a></td></tr>
    <tr><td>bar bar</td>
     <td><a class="deleteRowButton">delete row</a></td></tr>
    <tr><td>bazmati</td>
     <td><a class="deleteRowButton">delete row</a></td></tr>
  </table>
</body>
</html>

see it in action


$('#myTable tr').click(function(){
    $(this).remove();
    return false;
});

Even a better one

$("#MyTable").on("click", "#DeleteButton", function() {
   $(this).closest("tr").remove();
});

try this for size

$(this).parents('tr').first().remove();

full listing:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
  <script type="text/javascript">
    $(document).ready(function() {
        $('.deleteRowButton').click(DeleteRow);
      });

    function DeleteRow()
    {
      $(this).parents('tr').first().remove();
    }
  </script>
</head>
<body>
  <table>
    <tr><td>foo</td>
     <td><a class="deleteRowButton">delete row</a></td></tr>
    <tr><td>bar bar</td>
     <td><a class="deleteRowButton">delete row</a></td></tr>
    <tr><td>bazmati</td>
     <td><a class="deleteRowButton">delete row</a></td></tr>
  </table>
</body>
</html>

see it in action


Assuming you have a button/link inside of a data cell in your table, something like this would do the trick...

$(".delete").live('click', function(event) {
    $(this).parent().parent().remove();
});

This will remove the parent of the parent of the button/link that is clicked. You need to use parent() because it is a jQuery object, not a normal DOM object, and you need to use parent() twice, because the button lives inside a data cell, which lives inside a row....which is what you want to remove. $(this) is the button clicked, so simply having something like this will remove only the button:

$(this).remove();

While this will remove the data cell:

    $(this).parent().remove();

If you want to simply click anywhere on the row to remove it something like this would work. You could easily modify this to prompt the user or work only on a double-click:

$(".delete").live('click', function(event) {
    $(this).parent().remove();
});

Hope that helps...I struggled on this a bit myself.


Is the following acceptable:

$('#myTableRow').remove();

$('#myTable tr').click(function(){
    $(this).remove();
    return false;
});

Even a better one

$("#MyTable").on("click", "#DeleteButton", function() {
   $(this).closest("tr").remove();
});

function removeRow(row) {
    $(row).remove();
}

<tr onmousedown="removeRow(this)"><td>Foo</td></tr>

Maybe something like this could work as well? I haven't tried doing something with "this", so I don't know if it works or not.


Assuming you have a button/link inside of a data cell in your table, something like this would do the trick...

$(".delete").live('click', function(event) {
    $(this).parent().parent().remove();
});

This will remove the parent of the parent of the button/link that is clicked. You need to use parent() because it is a jQuery object, not a normal DOM object, and you need to use parent() twice, because the button lives inside a data cell, which lives inside a row....which is what you want to remove. $(this) is the button clicked, so simply having something like this will remove only the button:

$(this).remove();

While this will remove the data cell:

    $(this).parent().remove();

If you want to simply click anywhere on the row to remove it something like this would work. You could easily modify this to prompt the user or work only on a double-click:

$(".delete").live('click', function(event) {
    $(this).parent().remove();
});

Hope that helps...I struggled on this a bit myself.


$('#myTable tr').click(function(){
    $(this).remove();
    return false;
});

Even a better one

$("#MyTable").on("click", "#DeleteButton", function() {
   $(this).closest("tr").remove();
});

$('tr').click(function()
 {
  $(this).remove();
 });

i think you will try the above code, as it work, but i don't know why it work for sometime and then the whole table is removed. i am also trying to remove the row by click the row. but could not find exact answer.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html-table

Table column sizing DataTables: Cannot read property 'length' of undefined TypeError: a bytes-like object is required, not 'str' in python and CSV How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3? Sorting table rows according to table header column using javascript or jquery How to make background of table cell transparent How to auto adjust table td width from the content bootstrap responsive table content wrapping How to print table using Javascript?