Alvin Alvin - 21 days ago 7
HTML Question

Click a button on the row of the table and remove the row using javascript

<table id="myList">
<thead>
<tr>
<th>Product ID</th>
<th>Product Name</th>
<th>Quantity</th>
<th>&nbsp;</th>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td>Hello</td>
<td>2</td>
<td><button>Delete</button></td>
</tr>
</tbody>
</table>


I currently have a row in the table. I have a button on the very last column of the row. How do I remove/delete the row when i click the button and invoke a function?

Answer

You can use rowIndex to find which row need to be deleted.

Use deleteRow method to delete the row

Hope this snippet will be useful.

Here x will be the button

x.parentElement will be the td which contain the button

x.parentElement.parentElement will be the tr which need to be deleted

function delRow(x){
   document.getElementById("myList").deleteRow(x.parentElement.parentElement.rowIndex);
    }

JSFIDDLE