เมธอด insertRow() คืออะไร?
เมธอด insertRow(index) ของออบเจ็กต์ตาราง (HTMLTableElement) ใช้ **สร้างเอลิเมนต์ <tr> ว่าง** และ **แทรกเข้าไปในตาราง** ตามตำแหน่งที่ระบุ คืนค่า HTMLTableRowElement ที่สร้างขึ้น
รูปแบบการใช้งาน (Syntax)
tableElement.insertRow(index)
index(Integer, optional): ตำแหน่งที่จะแทรก (0-based)- ไม่ระบุ หรือ -1: แทรกที่ **ท้ายตาราง** (ก่อน tfoot)
- 0: แทรกที่ **ด้านบนสุด** (หลัง thead ถ้ามี)
- ค่าอื่น: แทรกก่อนแถว index นั้น
- คืนค่า:
HTMLTableRowElement(แถวที่สร้างใหม่) - โยน Exception:
IndexSizeErrorหาก index ไม่ถูกต้อง
ตัวอย่าง: เพิ่มแถวใหม่ที่ตำแหน่งที่ 2
<!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; }
การเพิ่มเซลล์เข้าไปในแถวใหม่ (insertCell)
var row = table.insertRow(-1); // เพิ่มท้าย
var cell1 = row.insertCell(0); // เซลล์แรก
cell1.textContent = 'ข้อมูล 1';
var cell2 = row.insertCell(1); // เซลล์ที่สอง
cell2.textContent = 'ข้อมูล 2';
// row.insertCell(-1) เพิ่มเซลล์ท้ายแถว
ตัวอย่างครบวงจร: ฟอร์มเพิ่มข้อมูลในตาราง
<!DOCTYPE html>
<html>
<body>
<h2>เพิ่มนักเรียน</h2>
<form id="studentForm" onsubmit="addStudent(event)">
<input type="text" name="name" placeholder="ชื่อ" required>
<input type="text" name="id" placeholder="เลขที่" required>
<button type="submit">เพิ่ม</button>
</form>
<table id="studentTable" border="1" style="margin-top:1rem; border-collapse:collapse;">
<thead><tr><th>ชื่อ</th><th>เลขที่</th><th>จัดการ</th></tr></thead>
<tbody></tbody>
</table>
<script>
var table = document.getElementById('studentTable');
var tbody = table.tBodies[0] || table.createTBody(); // สร้าง tbody ถ้ายังไม่มี
function addStudent(event) {
event.preventDefault();
var form = event.target;
var name = form.name.value.trim();
var id = form.id.value.trim();
if (!name || !id) return;
var row = tbody.insertRow(-1); // เพิ่มท้าย tbody
row.innerHTML = '<td>' + escapeHtml(name) + '</td><td>' + escapeHtml(id) + '</td><td><button onclick="this.closest(\'tr\').remove()">ลบ</button></td>';
form.reset();
form.name.focus();
}
function escapeHtml(text) {
var div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
</script>
</body>
</html>
ข้อควรระวัง
insertRow()สร้าง<tr>**ว่างเปล่า** ต้องเพิ่ม<td>/<th>เองด้วยinsertCell()หรือinnerHTML- ดัชนี (index) นับรวมทุกแถวในตาราง (
thead,tbody,tfoot) - แทรกใน
<tbody>เฉพาะ: ใช้tbody.insertRow(index)แทน (เฉพาะแถวใน tbody นั้น) - ใช้
-1หรือไม่ระบุ index เพื่อเพิ่มท้าย (สะดวกที่สุด)