The deleteRow()
method removes the row at the specified index from a table.
deleteRow |
Yes | Yes | Yes | Yes | Yes |
tableObject.deleteRow(index)
Value | Description |
---|---|
index | Required in Firefox and Opera, optional in IE, Chrome and Safari. An integer to the position starting at 0 of the row to delete. |
No return value
The following code shows how to delete the row you click on.
<!DOCTYPE html>
<html>
<head>
<style>
table, td {<!-- w w w .ja va2 s .co m-->
border: 1px solid black;
}
</style>
</head>
<body>
<table id="myTable">
<tr>
<td>Row 1</td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
</tr>
<tr>
<td>Row 2</td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
</tr>
<tr>
<td>Row 3</td>
<td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
</tr>
</table>
<script>
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to add and delete row(s).
<!DOCTYPE html>
<html>
<head>
<style>
table, td {<!--from ww w . j a va 2 s. c o m-->
border: 1px solid black;
}
</style>
</head>
<body>
<table id="myTable">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
</table>
<br>
<button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button>
<script>
function myCreateFunction() {
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
}
function myDeleteFunction() {
document.getElementById("myTable").deleteRow(0);
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to delete the first row in a table.
<!DOCTYPE html>
<html>
<head>
<style>
table, td {<!--from w w w . j ava 2s. com-->
border: 1px solid black;
}
</style>
</head>
<body>
<table id="myTable">
<tr>
<td>cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>cell 3</td>
<td>cell 4</td>
</tr>
</table>
<br>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
document.getElementById("myTable").deleteRow(0);
}
</script>
</body>
</html>
The code above is rendered as follows: