Shalinka Randeniya
Shalinka Randeniya

Reputation: 173

How delete a html table row using javascript?

I want to delete a row when i click the glyphicon-trash. I tried many ways but still cant get row index properly.

<table class="table table-bordered" id="table_GemList">
<thead>
  <col style="width: 25%">
  <col style="width: 25%">
  <col style="width: 25%">
  <col style="width: 25%">
</thead>
<tbody id="GemListBody">
<tr>
  <td>Oval</td>
  <td>Red</td>
  <td>2.23</td>
  <td><span class="glyphicon glyphicon-trash"></span></td>
</tr>
<tr>
  <td>Box</td>
  <td>Pink</td>
  <td>2.23</td>
  <td><span class="glyphicon glyphicon-trash"></span></td>
</tr>
</tbody>
</table>

---------- My code

 $(document).on("click", ".glyphicon-trash", function () {

        var d = $(this).parentNode.parentNode.rowIndex;
        document.getElementById("table_GemList").deleteRow(d);

});

Upvotes: 1

Views: 2419

Answers (5)

Ripun
Ripun

Reputation: 210

you can simply delete the parent in which trash icons is there by below jquery code

 $(document).on("click", ".glyphicon-trash", function (){
 $(this).parent().parent().remove(); // remove row

});

Upvotes: 0

Ram
Ram

Reputation: 144729

$(this) returns a jQuery object. You can't directly read the properties of the collection's items that way. In fact you shouldn't wrap the element with the jQuery constructor as you don't want to use the jQuery APIs.

var d = this.parentNode.parentNode.rowIndex;

Since you are using jQuery, you can simply use the closest and remove methods.

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

Upvotes: 3

Mario Araque
Mario Araque

Reputation: 4572

This should works.

$(document).on("click", ".glyphicon-trash", function () {
  $(this).parents('tr:first').remove();
});

Upvotes: 0

Negom
Negom

Reputation: 318

Maybe this helps....

 $(document).on("click", ".glyphicon-trash", function ()
 {
     $(this).closest("tr").remove(); // remove row
 });

Upvotes: 0

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28475

You need to update

var d = $(this).parentNode.parentNode.rowIndex;
document.getElementById("table_GemList").deleteRow(d);

to

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

For reference on closest() - https://api.jquery.com/closest/

For reference on remove() - https://api.jquery.com/remove/

Upvotes: 2

Related Questions