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

วัตถุ TableRow (<tr>) ใน HTML DOM: คุณสมบัติและเมธอด

วัตถุ TableRow (HTMLTableRowElement) คืออะไร?

วัตถุ TableRow ใน HTML DOM แทนเอลิเมนต์ <tr> (Table Row) ใช้จัดการแถวของตาราง: เพิ่ม/ลบเซลล์, เข้าถึงตำแหน่งแถวในตารางหรือใน section

การสร้าง TableRow ด้วย JavaScript

var tr = document.createElement('TR'); // หรือ 'tr'
tr.innerHTML = '<td>เซลล์ 1</td><td>เซลล์ 2</td>';
table.tBodies[0].appendChild(tr); // เพิ่มใน tbody แรก

คุณสมบัติ (Properties) สำคัญ

คุณสมบัติ คำอธิบาย
rowIndexตำแหน่งของแถวใน **คอลเลกชัน rows ของตารางทั้งหมด** (รวม thead, tbody, tfoot) - Read-only
sectionRowIndexตำแหน่งของแถวใน **คอลเลกชัน rows ของ section ปัจจุบัน** (thead, tbody, หรือ tfoot) - Read-only
cellsHTMLCollection ของเซลล์ (<td> และ <th>) ในแถวนี้ - Read-only

เมธอด (Methods) สำคัญ

เมธอด คำอธิบาย
insertCell(index)สร้าง <td> ว่างและแทรกในแถว คืนค่า HTMLTableCellElement. index ไม่ระบุ/-1 = ท้ายแถว
deleteCell(index)ลบเซลล์ที่ index ที่ระบุ. โยน IndexSizeError หาก index ไม่ถูกต้อง

ตัวอย่าง: สร้างแถวใหม่และเพิ่มเซลล์

<!DOCTYPE html>
<html>
<style>
  body { color: #000; background: lightblue; height: 100vh; text-align: center; }
  table { margin: 2rem auto; border-collapse: collapse; width: 400px; }
  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; }


การเข้าถึงเซลล์ในแถว (row.cells)

var row = table.rows[1]; // แถวที่ 2
var cells = row.cells; // HTMLCollection ของ td/th

// อ่านค่าเซลล์แรก
console.log(cells[0].textContent);

// วนลูปเซลล์ทั้งแถว
for (var i = 0; i < cells.length; i++) {
  console.log('Cell ' + i + ':', cells[i].textContent);
}

การลบเซลล์ (deleteCell)

var row = table.rows[1];
row.deleteCell(0); // ลบเซลล์แรก
row.deleteCell(-1); // ลบเซลล์สุดท้าย (บางเบราว์เซอร์รองรับ)

ข้อควรระวัง

  • rowIndex และ sectionRowIndex เป็น **Read-only** ไม่สามารถตั้งค่าได้
  • insertCell() สร้าง <td> เสมอ (ไม่ใช่ <th>) หากต้องการ th ให้สร้างแยก: document.createElement('TH')
  • การลบเซลล์ด้วย deleteCell() จะเปลี่ยน cells collection ทันที
  • แถวที่สร้างด้วย createElement('TR') ยังไม่ได้อยู่ในตาราง ต้อง appendChild หรือ insertBefore เข้า <tbody>, <thead>, หรือ <tfoot>