คุณสมบัติ tFoot คืออะไร?
คุณสมบัติ tFoot ของออบเจ็กต์ตาราง (HTMLTableElement) คืนค่า **เอลิเมนต์ <tfoot>** ของตาราง (ถ้ามี) หรือ null หากไม่มี ใช้สำหรับเข้าถึง/จัดการท้ายตารางโดยตรง
รูปแบบการใช้งาน (Syntax)
// อ่าน
var tfoot = tableElement.tFoot; // HTMLTableSectionElement หรือ null
// ตรวจสอบว่ามี tfoot หรือไม่
if (table.tFoot) { ... }
ตัวอย่าง: แสดงเนื้อหาของ tfoot
<!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; }
.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; }
การสร้าง tfoot ใหม่ (ถ้ายังไม่มี)
var tfoot = table.tFoot || table.createTFoot(); // ดึงที่มี หรือสร้างใหม่
tfoot.innerHTML = '<tr><td colspan="2">ท้ายตารางใหม่</td></tr>';
คุณสมบัติของ tfoot (HTMLTableSectionElement)
| คุณสมบัติ/เมธอด |
คำอธิบาย |
rows | HTMLCollection ของ <tr> ใน tfoot |
insertRow(index) | แทรกแถวใหม่ใน tfoot |
deleteRow(index) | ลบแถวใน tfoot |
rowIndex | ตำแหน่งของ tfoot ในตาราง (Read-only) |
ความสัมพันธ์กับเมธอดอื่นๆ
| เมธอด/คุณสมบัติ |
คำอธิบาย |
createTFoot() | สร้าง tfoot ใหม่ (หรือดึงที่มีอยู่) - คืนค่า tfoot |
deleteTFoot() | ลบ tfoot - หลังลบ table.tFoot จะเป็น null |
tFoot | คุณสมบัติอ่านอย่างเดียว - เข้าถึง tfoot ปัจจุบัน |
ความสำคัญของ <tfoot> ใน HTML
- **Placement:** ใน HTML เขียนก่อน
<tbody> ก็ได้ (HTML5) แต่เบราว์เซอร์จะ **แสดงท้ายตารางเสมอ**
- **Semantic:** บอกว่าเป็นส่วนสรุป/ท้ายตาราง (Totals, Averages, Notes)
- **Printing:** บางเบราว์เซอร์พิมพ์
<tfoot> ท้ายทุกหน้า
- **Accessibility:** Screen readers ใช้ tfoot เพื่อบอกสรุปข้อมูล
ข้อควรระวัง
tFoot เป็น **Read-only** ไม่สามารถกำหนด table.tFoot = ... ได้ (ใช้ createTFoot() แทน)
- ตารางมี
<tfoot> ได้ **สูงสุด 1 ตัว**
- ใช้
table.tFoot.rows เพื่อเข้าถึงแถวใน tfoot
- ต่างจาก
tBodies ที่เป็น Collection (หลายตัวได้) tHead และ tFoot เป็น Element เดียว (หรือ null)
กรณีใช้งานจริง
- **Auto-summary:** คำนวณผลรวมจาก tbody แล้วอัปเดต tfoot
- **Toggle Footer:** ซ่อน/แสดงแถวสรุปตามการตั้งค่าผู้ใช้
- **Export/Print:** จัดการ tfoot แยกต่างหากเมื่อ Export PDF/Print