วัตถุ TableData (HTMLTableCellElement) คืออะไร?
วัตถุ TableData ใน HTML DOM แทนเอลิเมนต์ <td> (Table Data Cell) ใช้สำหรับเซลล์ข้อมูลในตาราง มีคุณสมบัติสำหรับการขยายเซลล์ (colSpan, rowSpan) และเชื่อมโยงกับ Header (headers)
การสร้าง TableData ด้วย JavaScript
var td = document.createElement('TD'); // หรือ 'td'
td.textContent = 'ข้อมูลเซลล์';
tr.appendChild(td); // เพิ่มในแถว (tr)
คุณสมบัติ (Properties) สำคัญ
| คุณสมบัติ | คำอธิบาย |
|---|---|
cellIndex | ตำแหน่งเซลล์ในแถว (0-based) - Read-only |
colSpan | จำนวนคอลัมน์ที่ขยาย (อ่าน/เขียนได้) - ตรงกับ colspan attribute |
rowSpan | จำนวนแถวที่ขยาย (อ่าน/เขียนได้) - ตรงกับ rowspan attribute |
headers | รายการ id ของ header cells ที่เกี่ยวข้อง (space-separated) - อ่าน/เขียนได้ |
ตัวอย่าง: สร้างเซลล์ข้อมูลใหม่
<!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; }
การใช้งาน colSpan และ rowSpan
colSpan: ขยายเซลล์แนวนอน (Merge Columns)
<td colspan="2">ข้าม 2 คอลัมน์</td>
// JS:
td.colSpan = 2;
rowSpan: ขยายเซลล์แนวตั้ง (Merge Rows)
<td rowspan="3">ข้าม 3 แถว</td>
// JS:
td.rowSpan = 3;
การใช้งาน headers Attribute (Accessibility)
ระบุ id ของ <th> ที่เกี่ยวข้องกับเซลล์นี้ (คั่นด้วยช่องว่าง):
<th id="h-name">ชื่อ</th>
<th id="h-age">อายุ</th>
<td headers="h-name h-age">ข้อมูลที่เกี่ยวกับทั้งชื่อและอายุ</td>
ข้อควรระวัง
cellIndexเป็น Read-only คำนวณจากตำแหน่งในแถวโดยอัตโนมัติcolSpanและrowSpanต้องเป็นจำนวนเต็ม ≥ 1 (ค่า 0 จะถูกทำให้เป็น 1)- การตั้งค่า
colSpan/rowSpanผ่าน JS จะอัปเดต attribute และ Layout ทันที headersattribute ช่วย Screen Reader เชื่อมโยงข้อมูลกับหัวข้อที่ถูกต้อง สำคัญสำหรับตารางซับซ้อน<td>ไม่มีคุณสมบัติscope(มีเฉพาะ<th>)
คุณสมบัติร่วมของ th และ td (HTMLTableCellElement)
| คุณสมบัติ | th | td |
|---|---|---|
cellIndex | ✅ | ✅ |
colSpan | ✅ | ✅ |
rowSpan | ✅ | ✅ |
headers | ✅ | ✅ |
scope | ✅ | ❌ |
abbr | ✅ | ❌ (Non-standard) |