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

เมธอด deleteCaption() ของตารางใน HTML DOM: ลบคำอธิบายตาราง <caption>

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

เมธอด deleteCaption() ของออบเจ็กต์ตาราง (HTMLTableElement) ใช้ **ลบเอลิเมนต์ <caption> แรกที่พบ** ออกจากตาราง หากตารางไม่มี <caption> เมธอดนี้จะไม่ทำอะไร (ไม่โยน Error)

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

tableElement.deleteCaption()

ไม่มีพารามิเตอร์, ไม่คืนค่า (undefined)

ตัวอย่าง: ลบ Caption

<!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; font-size: 1.2rem; 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; }


เมธอดคู่ควร: createCaption()

หากต้องการสร้าง <caption> ใหม่หลังลบ ใช้ createCaption():

var caption = table.createCaption(); // สร้าง caption ใหม่ (หรือดึงที่มีอยู่)
caption.innerHTML = 'คำอธิบายใหม่';
caption.style.captionSide = 'bottom'; // วางด้านล่าง

คุณสมบัติ caption ของตาราง

ออบเจ็กต์ตารางมีคุณสมบัติ caption ที่คืนค่า <caption> ปัจจุบัน (หรือ null):

var cap = table.caption; // HTMLTableCaptionElement หรือ null
if (cap) cap.remove(); // วิธีอื่น: ใช้ remove() method ของ Element

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

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

ข้อควรระวัง

  • deleteCaption() ลบ **เฉพาะ <caption> แรก** (มีได้สูงสุด 1 ต่อตาราง ตามมาตรฐาน)
  • ไม่สามารถ Undo ได้ ต้องสร้างใหม่ด้วย createCaption()
  • ใช้ table.caption ตรวจสอบว่ามี caption อยู่หรือไม่ ก่อนลบ/สร้าง
  • <caption> ควรเป็นลูกแรกของ <table> (HTML Standard)

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

  • **Editable Table:** ให้ผู้ใช้เพิ่ม/แก้ไข/ลบ Caption ได้
  • **Dynamic Report:** เปลี่ยน Caption ตามเงื่อนไข (ภาษา, ช่วงเวลา, ผู้ใช้)
  • **Print Layout:** ลบ Caption ก่อนพิมพ์ หากไม่ต้องการแสดง