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

เมธอด createTHead() ของตารางใน HTML DOM: สร้างหัวตาราง <thead>

เมธอด createTHead() คืออะไร?

เมธอด createTHead() ของออบเจ็กต์ตาราง (HTMLTableElement) ใช้ **สร้างเอลิเมนต์ <thead> ว่าง** และเพิ่มเข้าไปในตาราง (วางก่อน <tbody> แรก) หากตารางมี <thead> อยู่แล้ว จะคืนค่า thead เดิม (ไม่สร้างใหม่)

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

tableElement.createTHead()

คืนค่า: HTMLTableSectionElement (เอลิเมนต์ 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; }


การใช้งานร่วมกับ deleteTHead()

function resetHeader() {
  var table = document.querySelector('table');
  table.deleteTHead();        // ลบ thead เก่า (ถ้ามี)
  var thead = table.createTHead(); // สร้างใหม่
  thead.innerHTML = '<tr><th>หัวข้อใหม่</th></tr>';
}

ความสำคัญของ <thead>

  • **Semantic:** บอกเบราว์เซอร์/スクリーンリーダー ว่าเป็นหัวตาราง
  • **Printing:** เมื่อพิมพ์ตารางยาวหลายหน้า <thead> จะแสดงซ้ำทุกหน้า (Browser support varies)
  • **Scrolling:** ใช้ CSS ทำให้ <tbody> เลื่อนได้ แต่อยู่ <thead> คงที่ (Sticky header)
  • **Sorting/Filtering:** JavaScript libraries มักต้องการ <thead> เพื่อทำงาน

สร้างหัวตารางหลายแถว (Multi-row Header)

var thead = table.createTHead();
// แถวที่ 1: กลุ่มหลัก
var row1 = thead.insertRow(0);
row1.innerHTML = '<th colspan="2">ข้อมูลส่วนตัว</th><th colspan="2">ติดต่อ</th>';
// แถวที่ 2: รายละเอียด
var row2 = thead.insertRow(1);
row2.innerHTML = '<th>ชื่อ</th><th>นามสกุล</th><th>อีเมล</th><th>โทร</th>';

เมธอดจัดการส่วนของตาราง (สรุป)

ส่วน สร้าง (Create) ลบ (Delete)
<caption>createCaption()deleteCaption()
<thead>createTHead()deleteTHead()
<tfoot>createTFoot()deleteTFoot()

ข้อควรระวัง

  • createTHead() สร้าง <thead> **ว่างเปล่า** ต้องใส่ <tr> และ <th> เอง
  • มีได้สูงสุด **1 <thead> ต่อตาราง**
  • วางตำแหน่งอัตโนมัติ: ก่อน <tbody> แรก (หรือก่อน <tfoot> ถ้าไม่มี tbody)
  • ใช้ table.tHead เพื่อเข้าถึง thead ที่มีอยู่ (คืนค่า null ถ้าไม่มี)