Phương thức deleteRow() của đối tượng HTMLTableElement xóa một hàng <tr> khỏi bảng tại chỉ số (index) chỉ định. Chỉ số tính từ 0, duyệt theo thứ tự DOM (thead → tbody → tfoot).
Cú pháp
tableElement.deleteRow(index)
index: Số nguyên, vị trí hàng cần xóa. Nếuindex= -1, xóa hàng cuối cùng (hỗ trợ hầu hết trình duyệt hiện đại).- Nếu
indexvượt quá số hàng, ném lỗiIndexSizeError.
Ví dụ: Xóa hàng thứ 2 (index 1)
<!DOCTYPE html>
<html>
<style>
body { color: #000; background: lightblue; height: 100vh; text-align: center; }
table { margin: 2rem auto; border-collapse: collapse; }
.btn { background: #db133a; border: none; height: 2rem; border-radius: 2px; width: 40%; display: block; color: #fff; outline: none; cursor: pointer; margin: 1rem auto; }
.show { font-size: 1.2rem; margin-top: 1rem; }
<body>
<h1>Demo: table.deleteRow()</h1>
<table border="2" id="demoTable">
<thead>
<tr><th>Tên</th><th>Mã SV</th></tr>
</thead>
<tbody>
<tr><td>An</td><td>071717</td></tr>
<tr><td>Bình</td><td>031717</td></tr>
</tbody>
</table>
<button onclick="removeRow()" class="btn">Xóa hàng index 1</button>
<div class="show" id="msg"></div>
<script>
function removeRow() {
var table = document.getElementById('demoTable');
try {
table.deleteRow(1); // Xóa hàng index 1 (hàng header là index 0)
document.getElementById('msg').textContent = 'Đã xóa hàng index 1';
} catch (e) {
document.getElementById('msg').textContent = 'Lỗi: ' + e.message;
}
}
</script>
</body>
</html>
Kết quả:
- Ban đầu: 3 hàng (1 header + 2 dữ liệu).
- Sau xóa index 1: Header còn lại, hàng "An" bị xóa, hàng "Bình" trở thành index 1 mới.
deleteRow()xóa cả hàng trong<thead>,<tbody>,<tfoot>— tùy vào index.- Để xóa hàng trong
tbodycụ thể:table.tBodies[0].deleteRow(index)(index tính trong tbody đó). - Phương thức này **thay đổi DOM trực tiếp**, không cần
removeChild(). - Không thể hoàn tác (undo) trừ khi tự lưu trạng thái trước đó.
insertRow(index): Thêm hàng mới.deleteTHead(),deleteTFoot(),deleteCaption(): Xóa các phần khác.