在JavaScript中,可使用remove()方法从HTML表中删除表行。remove()方法删除选定的元素以及文本和子节点;此方法还会删除所选元素的数据和事件。
语法:
node.remove()
示例1:首先根据id值选择行,然后使用remove()方法删除它。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
table tr {
background:#e46060ed;
color: white;
}
td {
padding:10px;
}
</style>
</head>
<center>
<h2 style="color:red;" >使用JavaScript删除表中的表行</h2>
<table>
<tr>
<th>S.No</th>
<th>Title</th>
<th>id</th>
</tr>
<tr id = "row1">
<td>01</td>
<td>Hello</td>
<th>id_1</th>
</tr>
<tr>
<td>02</td>
<td>Hello World!</td>
<th>id_2</th>
</tr>
</table>
<br>
<button onclick = "Hello()">点击这里</button>
<script>
function Hello() {
document.getElementById("row1").remove();
}
</script>
</center>
</body>
</html>
效果图:
示例2:首先根据标签名选择行,然后使用remove()方法通过索引删除适当的元素
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
table tr {
background:#e46060ed;
color: white;
}
td {
padding:10px;
}
</style>
</head>
<center>
<h2 style="color:red;" >使用JavaScript删除表中的表行</h2>
<table>
<tr>
<th>S.No</th>
<th>Title</th>
<th>id</th>
</tr>
<tr id = "row1">
<td>01</td>
<td>Hello</td>
<th>id_1</th>
</tr>
<tr>
<td>02</td>
<td>Hello World!</td>
<th>id_2</th>
</tr>
<tr>
<td>03</td>
<td>Hello World!</td>
<th>id_3</th>
</tr>
</table>
<br>
<button onclick = "Hello()">点击这里</button>
<script>
function Hello() {
document.getElementsByTagName("tr")[3].remove();
}
</script>
</center>
</body>
</html>
效果图:
推荐阅读: