เมธอด createCaption() คืออะไร?
เมธอด createCaption() ของออบเจ็กต์ตาราง (HTMLTableElement) ใน HTML DOM ใช้สร้างเอลิเมนต์ <caption> ว่างๆ และเพิ่มเข้าไปในตารางโดยอัตโนมัติ หากตารางมี <caption> อยู่แล้ว จะคืนค่า caption เดิม (ไม่สร้างใหม่)
รูปแบบการใช้งาน (Syntax)
tableElement.createCaption()
คืนค่า: ออบเจ็กต์ HTMLTableCaptionElement (เอลิเมนต์ caption ที่สร้างหรือมีอยู่แล้ว)
ตัวอย่างการใช้งาน
<!DOCTYPE html>
<html>
<style>
body { color: #000; background: lightblue; height: 100vh; text-align: center; }
table { margin: 2rem auto; border-collapse: collapse; }
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; }
คุณสมบัติเพิ่มเติมของ <caption>
captionSide(CSS): กำหนดตำแหน่ง caption -top(ค่าเริ่มต้น) หรือbottomalign(Deprecated): ใช้ CSStext-alignแทน
เมธอดที่เกี่ยวข้อง
| เมธอด | คำอธิบาย |
|---|---|
deleteCaption() | ลบ <caption> แรกที่พบในตาราง |
createTHead() | สร้าง <thead> |
createTFoot() | สร้าง <tfoot> |
createTBody() | สร้าง <tbody> |
insertRow() | แทรกแถวใหม่ <tr> |
deleteRow() | ลบแถว <tr> |
การใช้งานร่วมกับ deleteCaption()
function toggleCaption() {
var table = document.querySelector('table');
if (table.caption) {
table.deleteCaption(); // ลบถ้ามีอยู่แล้ว
} else {
var cap = table.createCaption();
cap.innerHTML = "ข้อมูลใหม่";
}
}