Thuộc tính tHead của đối tượng HTMLTableElement trả về phần tử <thead> của bảng (nếu có), hoặc null nếu bảng chưa có thead. Đây là cách truy xuất trực tiếp thead thay vì dùng querySelector.
Cú pháp
var thead = tableElement.tHead;
Ví dụ: Lấy và hiển thị nội dung thead
<!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.tHead</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>
<tfoot>
<tr><td colspan="2">Tổng: 2</td></tr>
</tfoot>
</table>
<button onclick="showHead()" class="btn">Hiện thead</button>
<div class="show" id="result"></div>
<script>
function showHead() {
var table = document.getElementById('demoTable');
var head = table.tHead;
if (head) {
document.getElementById('result').innerHTML = 'thead HTML: ' + head.innerHTML;
} else {
document.getElementById('result').textContent = 'Bảng không có thead';
}
}
</script>
</body>
</html>
Kết quả:
Nhấn nút → Hiển thị HTML của thead: <tr><th>Tên</th><th>Mã SV</th></tr>
Ứng dụng
- Kiểm tra bảng có header chưa:
if (table.tHead) ... - Thêm/sửa header động:
table.tHead.innerHTML = "..."hoặctable.createTHead()nếu chưa có. - Duyệt các ô header:
var cells = table.tHead.rows[0].cells;
Phương thức liên quan
createTHead(): Tạo thead nếu chưa có, trả về thead.deleteTHead(): Xóa thead.
Lưu ý: tHead là thuộc tính chỉ đọc (read-only) — không thể gán table.tHead = newHead. Dùng createTHead()/deleteTHead() để tạo/xóa.