Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

คุณสมบัติ tHead ของตารางใน HTML DOM: เข้าถึง <thead>

คุณสมบัติ tHead คืออะไร?

คุณสมบัติ tHead ของออบเจ็กต์ตาราง (HTMLTableElement) คืนค่า **เอลิเมนต์ <thead>** ของตาราง (ถ้ามี) หรือ null หากไม่มี ใช้สำหรับเข้าถึง/จัดการหัวตารางโดยตรง

รูปแบบการใช้งาน (Syntax)

// อ่าน
var thead = tableElement.tHead; // HTMLTableSectionElement หรือ null

// ตรวจสอบว่ามี thead หรือไม่
if (table.tHead) { ... }

ตัวอย่าง: แสดงเนื้อหาของ thead

<!DOCTYPE html>
<html>
<style>
  body { color: #000; background: lightblue; height: 100vh; text-align: center; }
  table { margin: 2rem auto; border-collapse: collapse; }
  th, td { border: 1px solid #333; padding: 8px; }
  caption { color: #db133a; font-weight: bold; padding: 0.5rem; }
  .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; }


การสร้าง thead ใหม่ (ถ้ายังไม่มี)

var thead = table.tHead || table.createTHead(); // ดึงที่มี หรือสร้างใหม่
thead.innerHTML = '<tr><th>หัวข้อ 1</th><th>หัวข้อ 2</th></tr>';

คุณสมบัติของ thead (HTMLTableSectionElement)

คุณสมบัติ/เมธอด คำอธิบาย
rowsHTMLCollection ของ <tr> ใน thead
insertRow(index)แทรกแถวใหม่ใน thead
deleteRow(index)ลบแถวใน thead
rowIndexตำแหน่งของ thead ในตาราง (Read-only)

ความสัมพันธ์กับเมธอดอื่นๆ

เมธอด/คุณสมบัติ คำอธิบาย
createTHead()สร้าง thead ใหม่ (หรือดึงที่มีอยู่) - คืนค่า thead
deleteTHead()ลบ thead - หลังลบ table.tHead จะเป็น null
tHeadคุณสมบัติอ่านอย่างเดียว - เข้าถึง thead ปัจจุบัน

ข้อควรระวัง

  • tHead เป็น **Read-only** ไม่สามารถกำหนด table.tHead = ... ได้ (ใช้ createTHead() แทน)
  • ตารางมี <thead> ได้ **สูงสุด 1 ตัว**
  • หากมีหลาย <thead> ใน HTML (Invalid) เบราว์เซอร์จะรวมเป็น 1 ตัวอัตโนมัติ
  • ใช้ table.tHead.rows เพื่อเข้าถึงแถวใน thead

กรณีใช้งานจริง

  • **Sticky Header:** ใช้ table.tHead เพื่อเพิ่ม CSS position: sticky; top: 0
  • **Dynamic Sorting:** อ่าน header cells จาก table.tHead.rows[0].cells เพื่อสร้างปุ่มเรียงลำดับ
  • **Clone Table:** คัดลอกโครงสร้าง thead ไปตารางใหม่
  • **Validation:** ตรวจสอบว่าตารางมี header ครบก่อนประมวลผล