คุณสมบัติ headers คืออะไร?
คุณสมบัติ headers ของเอลิเมนต์ <td> (และ <th>) ใช้ **ระบุ id ของ Header Cell (<th>) ที่เกี่ยวข้อง** กับเซลล์ข้อมูลนี้ ใช้ **Space-separated list** ของ id เพื่อเชื่อมโยงหลาย Header ได้
วัตถุประสงค์หลัก: **Accessibility (Screen Readers)** - ช่วยให้ผู้ใช้พิการสายตาเข้าใจว่าเซลล์ข้อมูลนี้สัมพันธ์กับหัวข้อไหนบ้าง โดยเฉพาะตารางซับซ้อนที่มี Header หลายระดับ
รูปแบบการใช้งาน (Syntax)
ใน HTML:
<td headers="header-id-1 header-id-2">ข้อมูล</td>
ใน JavaScript (DOM Property):
// อ่านค่า (String) var ids = tdElement.headers; // ตั้งค่า tdElement.headers = "id1 id2 id3";
ตัวอย่าง: ตารางที่มี Header หลายระดับ
<!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; }
.show { font-size: 1.2rem; margin-top: 1rem; }
ตัวอย่างตารางซับซ้อน: Header หลายระดับ (Multi-level Headers)
<table>
<thead>
<tr>
<th id="h-name" rowspan="2">นักเรียน</th>
<th id="h-q1" colspan="2">ไตรมาส 1</th>
<th id="h-q2" colspan="2">ไตรมาส 2</th>
</tr>
<tr>
<th id="h-q1-mid" headers="h-q1">กลางภาค</th>
<th id="h-q1-final" headers="h-q1">ปลายภาค</th>
<th id="h-q2-mid" headers="h-q2">กลางภาค</th>
<th id="h-q2-final" headers="h-q2">ปลายภาค</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row" id="r1">สมชาย</th>
<td headers="h-q1 h-q1-mid r1">85</td>
<td headers="h-q1 h-q1-final r1">90</td>
<td headers="h-q2 h-q2-mid r1">88</td>
<td headers="h-q2 h-q2-final r1">92</td>
</tr>
</tbody>
</table>
แนวทางปฏิบัติที่ดี
- **ทุก
<th>ควรมีid** ที่ไม่ซ้ำกัน - **ทุก
<td>ควรมีheaders** อ้างอิง id ของ<th>ที่เกี่ยวข้อง - ใช้
scopeบน<th>ร่วมกับheadersบน<td>เพื่อความชัดเจนสูงสุด - ในตารางง่าย (1 ระดับ Header) ใช้
scope="col|row"ก็พอ ไม่ต้องheaders headersบน<th>ใช้ระบุ Header ระดับบนที่เกี่ยวข้อง (เหมือนตัวอย่าง Q1, Q2)
การเข้าถึงด้วย JavaScript
var td = document.querySelector('td');
console.log(td.headers); // String: "id1 id2"
// แปลงเป็น Array
var headerIds = td.headers.split(' ').filter(Boolean);
headerIds.forEach(function(id) {
var th = document.getElementById(id);
console.log('Related header:', th.textContent);
});