คอลเลกชัน rows คืออะไร?
คอลเลกชัน rows ของออบเจ็กต์ตาราง (HTMLTableElement) คืนค่า **HTMLCollection** ของเอลิเมนต์ <tr> **ทั้งหมด** ในตาราง รวมถึงแถวใน <thead>, <tbody>, <tfoot> เรียงตามลำดับในเอกสาร
รูปแบบการใช้งาน (Syntax)
tableElement.rows
คุณสมบัติของ rows Collection
| คุณสมบัติ |
คำอธิบาย |
length | จำนวนแถว <tr> ทั้งหมดในตาราง |
เมธอดของ rows Collection
| เมธอด |
คำอธิบาย |
[index] | เข้าถึงแถวตามดัชนี (0-based) |
item(index) | เหมือน [index] คืนค่า null หากเกิน |
namedItem(id) | เข้าถึงแถวตาม id attribute |
ตัวอย่าง: นับและเข้าถึงแถวทั้งหมด
<!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; }
.show { font-size: 1.2rem; margin-top: 1rem; }
ความแตกต่าง: table.rows vs tbody.rows
| คอลเลกชัน |
ขอบเขต |
กรณีใช้งาน |
table.rows | แถวทั้งหมดในตาราง (thead, tbody, tfoot) | นับรวม, ค้นหาแถวข้าม section |
tbody.rows | เฉพาะแถวใน <tbody> นั้นๆ | จัดการข้อมูลในกลุ่มเฉพาะ |
thead.rows | เฉพาะแถวใน <thead> | จัดการหัวตาราง |
tfoot.rows | เฉพาะแถวใน <tfoot> | จัดการท้ายตาราง |
การใช้งานจริง
- **วนลูปแถวทั้งตาราง:** สำหรับการค้นหา, กรอง, หรือส่งออกข้อมูล
- **เข้าถึงเซลล์:**
row.cells คืนค่า HTMLCollection ของ <td>/<th> ในแถวนั้น
- **เพิ่ม/ลบแถว:** ใช้
table.insertRow(), table.deleteRow() (ดูรายละเอียดในบทความถัดไป)
ข้อควรระวัง
rows เป็น **Live HTMLCollection** อัปเดตอัตโนมัติเมื่อ DOM เปลี่ยนแปลง
- ดัชนี (index) รวมทุก section เรียงจากบนลงล่าง
- การใช้
namedItem(id) ต้องการให้ <tr> มี id attribute