简体   繁体   中英

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);

});

$(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();

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/

Maybe this helps....

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

This should works.

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

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

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM