วัตถุ TableHeader (HTMLTableHeaderCellElement) คืออะไร?
วัตถุ TableHeader ใน HTML DOM แทนเอลิเมนต์ <th> (Table Header Cell) ใช้สำหรับหัวข้อคอลัมน์หรือแถว มีคุณสมบัติเฉพาะสำหรับตาราง เช่น scope, abbr, colSpan, rowSpan
การสร้าง TableHeader ด้วย JavaScript
var th = document.createElement('TH'); // หรือ 'th'
th.textContent = 'หัวข้อใหม่';
th.scope = 'col'; // หรือ 'row'
theadRow.appendChild(th);
คุณสมบัติ (Properties) สำคัญ
| คุณสมบัติ |
คำอธิบาย |
cellIndex | ตำแหน่งเซลล์ในแถว (0-based) - Read-only |
colSpan | จำนวนคอลัมน์ที่ขยาย (อ่าน/เขียนได้) - ตรงกับ colspan attribute |
rowSpan | จำนวนแถวที่ขยาย (อ่าน/เขียนได้) - ตรงกับ rowspan attribute |
scope | ขอบเขตของ Header: 'col', 'row', 'colgroup', 'rowgroup', '' (auto) - **สำคัญสำหรับ Accessibility** |
abbr | คำย่อ/คำอธิบายสั้น (อ่าน/เขียนได้) - ตรงกับ abbr attribute |
headers | รายการ id ของ header cells ที่เกี่ยวข้อง (space-separated) - สำหรับตารางซับซ้อน |
คุณสมบัติ scope: รายละเอียด
| ค่า scope |
ความหมาย |
ตัวอย่าง |
col | เป็นหัวข้อของคอลัมน์นี้ (ค่าเริ่มต้นสำหรับ th ใน thead) | <th scope="col">ชื่อ</th> |
row | เป็นหัวข้อของแถวนี้ (ใช้ใน tbody แรกคอลัมน์) | <th scope="row">สมชาย</th> |
colgroup | เป็นหัวข้อของกลุ่มคอลัมน์ (ใช้กับ colSpan > 1) | <th scope="colgroup" colspan="3">Q1</th> |
rowgroup | เป็นหัวข้อของกลุ่มแถว (ใช้กับ rowSpan > 1) | <th scope="rowgroup" rowspan="2">Group A</th> |
'' (ว่าง) | Auto - เบราว์เซอร์เดาเองจากตำแหน่ง | <th>Auto</th> |
ตัวอย่าง: สร้างหัวตารางแบบ Dynamic
<!DOCTYPE html>
<html>
<style>
body { color: #000; background: lightblue; height: 100vh; text-align: center; }
table { margin: 2rem auto; border-collapse: collapse; width: 400px; }
th, td { border: 1px solid #333; padding: 8px; }
.btn { background: #db133a; border: none; height: 2rem; border-radius: 2px; width: 40%; display: block; color: #fff; outline: none; cursor: pointer; margin: 1rem auto; }
การใช้งาน abbr และ headers สำหรับ Accessibility
<table>
<thead>
<tr>
<th id="h-name" abbr="ชื่อ" scope="col">ชื่อ-นามสกุล</th>
<th id="h-lang" abbr="ภาษา" scope="col">ภาษาที่ใช้</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row" id="r1">สมชาย</th> <!-- Row header -->
<td headers="h-lang">ไทย</td>
</tr>
</tbody>
</table>
ข้อควรระวัง
- ใช้
scope ให้ถูกต้อง: col สำหรับหัวคอลัมน์, row สำหรับหัวแถว
abbr ช่วย Screen Reader อ่านสั้นๆ แทนข้อความยาว
headers attribute บน <td> ใช้ระบุ id ของ <th> ที่เกี่ยวข้อง (สำหรับตารางซับซ้อน)
colSpan และ rowSpan ต้องเป็นตัวเลข ≥ 1