Remove a row from a HTML table in JavaScript

Description

The following code shows how to remove a row from a HTML table.

Example


<!--from   ww w.  ja v  a 2s .  com-->
<!DOCTYPE HTML>
<html>
<body>
<table border="1">
<thead>
<th>Name</th>
<th>Color</th>
</thead>
<tbody id="myBody">
<tr>
<td>A</td>
<td>B</td>
</tr>
<tr>
<td>C</td>
<td>D</td>
</tr>
</tbody>
</table>
<button id="add">Add Element</button>
<button id="remove">Remove Element</button>
<script>
var tableBody = document.getElementById("myBody");
document.getElementById("add").onclick = function() {
var row = tableBody.appendChild(document.createElement("tr"));
row.setAttribute("id", "newrow");
row.appendChild(document.createElement("td")).appendChild(document.createTextNode("X"));
row.appendChild(document.createElement("td")).appendChild(document.createTextNode("Y"));
};
document.getElementById("remove").onclick = function() {
var row = document.getElementById("newrow");
row.parentNode.removeChild(row);
}
</script>
</body>
</html>

Click to view the demo

The code above generates the following result.

Remove a row from a HTML table in JavaScript
Home »
  Javascript Tutorial »
    Tag »
      Table
Javascript Tutorial Table
Add new row to a HTML table in JavaScript
Change table structure with outerHTML in Ja...
Compare two table rows in JavaScript
Copy table row between two tables using inn...
Remove a row from a HTML table in JavaScrip...