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

เมธอด deleteRow() ของตารางใน HTML DOM: ลบแถว <tr>

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

เมธอด deleteRow(index) ของออบเจ็กต์ตาราง (HTMLTableElement) ใช้ **ลบแถว <tr>** ออกจากตาราง ตามดัชนี (index) ที่ระบุ ดัชนีเริ่มจาก 0 และนับรวมทุกแถวในตาราง (thead, tbody, tfoot)

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

tableElement.deleteRow(index)
  • index (Integer): ตำแหน่งแถวที่จะลบ (0 = แถวแรก)
  • คืนค่า: ไม่มี (undefined)
  • โยน Exception: IndexSizeError หาก index ติดลบ หรือเกินจำนวนแถว

ตัวอย่าง: ลบแถวที่ 2 (Index 1)

<!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; }
  .btn { background: #db133a; border: none; height: 2rem; border-radius: 2px; width: 40%; display: block; color: #fff; outline: none; cursor: pointer; margin: 1rem auto; }


การลบแถวสุดท้าย (Common Pattern)

function deleteLastRow() {
  var table = document.querySelector('table');
  if (table.rows.length > 0) {
    table.deleteRow(table.rows.length - 1);
  }
}

การลบหลายแถว (Loop Backwards)

function deleteRowsByCondition() {
  var table = document.querySelector('table');
  // ต้องลูปย้อนหลัง เพราะการลบจะเปลี่ยนดัชนีของแถวถัดไป
  for (var i = table.rows.length - 1; i >= 0; i--) {
    var row = table.rows[i];
    // ตัวอย่าง: ลบแถวที่มีค่าในเซลล์แรกเป็น "ลบ"
    if (row.cells[0].textContent.trim() === 'ลบ') {
      table.deleteRow(i);
    }
  }
}

เมธอดที่เกี่ยวข้อง

เมธอด คำอธิบาย
insertRow(index)แทรกแถวใหม่ <tr> ว่าง
deleteRow(index)ลบแถว <tr>
createTHead()สร้าง <thead>
deleteTHead()ลบ <thead>
createTFoot()สร้าง <tfoot>
deleteTFoot()ลบ <tfoot>
createCaption()สร้าง <caption>
deleteCaption()ลบ <caption>

ข้อควรระวัง

  • ลบแถวใน <thead> หรือ <tfoot> ได้ เช่นกัน (ถ้าดัชนีตรง)
  • หากตารางมี <tbody> หลายกลุ่ม ดัชนียังคงนับต่อเนื่องทุกแถว
  • การลบแถวจะลบเซลล์ (<td>/<th>) ภายในแถวนั้นด้วย
  • ใช้ try-catch ป้องกัน IndexSizeError หากไม่แน่ใจว่ามีแถวพอ