In this tutorial we will learn How To Delete Table Row by id with JavaScript. For this we can use HTML DOM Element remove() method along with getElementById() method and value property.
Table of Contents
remove() method
remove() method removes or deletes the HTML element or a node from DOM.
In this example remove() method is used to delete the row by it's id.
getElementById() method
getElementById() method selects or targets the HTML element based on it's id.
In this example getElementById() method is used to select the row of table using it's id.
value property
value property is used to set, update or get the value of input elements.
In this example it is used to get the id of row from the user through input tag.
HTML Code
HTML Code is given below, in this code we have a table tag with three rows, one input tag to take the id as an input and a button tag with onclick event.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Delete Table Row by id</title>
<style>
table,tr,th,td
{
border: 1px solid black;
padding: 5px;
}
table
{
border-collapse: collapse;
}
</style>
</head>
<body>
<table id="table">
<tr>
<th>Row Id</th>
<th>Name</th>
<th>Code</th>
</tr>
<tr id='row1'>
<td>row1</td>
<td>John</td>
<td>2832</td>
</tr>
<tr id='row2'>
<td>row2</td>
<td>Sara</td>
<td>2323</td>
</tr>
</table>
<br>
<input type="text" placeholder="Enter Row id:" id="rowId">
<br><br>
<button onclick="deleteRow()">Delete Row</button>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code, the code will be executed on a click of button with the help of onclick event.
In this code getElementById() method and value property are used to get the id of row from user. Then getElementById() method is used to select that row by it's id.
Then remove() method is used to delete the selected row of table.
If Else statements are used to check if row with given id exists or not.
<script>
function deleteRow()
{
var id = document.getElementById('rowId').value;
var row = document.getElementById(id);
if(row)
{
row.remove();
}
else
{
alert("Please Enter Correct Row Id!");
}
}
</script>
Demo
Video Tutorial
Watch video tutorial on How To Delete Table Row by id in JavaScript.