ออบเจ็กต์ table ของ HTML DOM แทนองค์ประกอบ <table> ในเอกสาร HTML ให้เข้าถึงและจัดการตารางได้ผ่าน JavaScript
ไวยากรณ์ (Syntax)
สร้างออบเจ็กต์ตารางใหม่:
document.createElement("TABLE");
คุณสมบัติ (Properties)
| คุณสมบัติ | คำอธิบาย |
|---|---|
| caption | คืนค่าองค์ประกอบ <caption> ของตาราง |
| tFoot | คืนค่าองค์ประกอบ <tfoot> ของตาราง |
| tHead | คืนค่าองค์ประกอบ <thead> ของตาราง |
เมธอด (Methods)
| เมธอด | คำอธิบาย |
|---|---|
| createCaption() | สร้าง <caption> ว่างและเพิ่มลงในตาราง |
| createTFoot() | สร้าง <tfoot> ว่างและเพิ่มลงในตาราง |
| createTHead() | สร้าง <thead> ว่างและเพิ่มลงในตาราง |
| deleteCaption() | ลบ <caption> ตัวแรกออกจากตาราง |
| deleteRow() | ลบแถว <tr> จากตาราง |
| deleteThead() | ลบ <thead> ออกจากตาราง |
| deleteTFoot() | ลบ <tfoot> ออกจากตาราง |
| insertRow() | สร้างแถว <tr> ว่างและเพิ่มลงในตาราง |
ตัวอย่างการใช้งาน
ตัวอย่างสร้างตารางแบบไดนามิกผ่าน JavaScript
<!DOCTYPE html>
<html>
<head>
<style>
body {
text-align: center;
background-color: #fff;
color: #0197F6;
}
h1 {
color: #23CE6B;
}
.btn {
background-color: #fff;
border: 1.5px dashed #0197F6;
height: 2rem;
border-radius: 2px;
width: 60%;
margin: 2rem auto;
display: block;
color: #0197F6;
outline: none;
cursor: pointer;
}
</style>
</head>
<body>
<h1>ตัวอย่าง DOM table Object</h1>
<button onclick="createTable()" class="btn">สร้างออบเจ็กต์ตาราง</button>
<script>
function createTable() {
var table = document.createElement("TABLE");
table.innerHTML = '<tr> <td>ข้อมูล 1</td> <td>ข้อมูล 2</td> </tr> <tr> <td>ข้อมูล 3</td> <td>ข้อมูล 4</td> </tr>';
table.setAttribute('border', "2");
table.style.margin = "2rem auto";
document.body.appendChild(table);
}
</script>
</body>
</html>
ผลลัพธ์
ก่อนคลิกปุ่ม - ไม่มีตาราง
หลังคลิกปุ่ม "สร้างออบเจ็กต์ตาราง" - ตาราง 2x2 ปรากฏขึ้นพร้อมข้อมูล
คำแนะนำ: ใช้เมธอดเหล่านี้แทนการจัดการ innerHTML โดยตรง เพื่อความปลอดภัยและประสิทธิภาพที่ดีกว่า