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

คอลเลกชัน tBodies ของ HTML DOM Table

คอลเลกชัน tBodies ของ HTML DOM Table ใช้สำหรับดึงคอลเลกชันขององค์ประกอบ <tbody> ทั้งหมดในตาราง (table) ภายในเอกสาร HTML

ไวยากรณ์ (Syntax)

object.tBodies

คุณสมบัติของ tBodies Collection

คุณสมบัติคำอธิบาย
lengthคืนจำนวนองค์ประกอบ <tbody> ในคอลเลกชัน

เมธอดของ tBodies Collection

เมธอดคำอธิบาย
[index]คืนองค์ประกอบ <tbody>> ตาม index ที่ระบุจากคอลเลกชัน
item(index)คืนองค์ประกอบ <tbody> ตาม index ที่ระบุจากคอลเลกชัน
namedItem(id)คืนองค์ประกอบ <tbody> ตาม id ที่ระบุจากคอลเลกชัน

ตัวอย่างการใช้งาน

ตัวอย่างด้านล่างแสดงการนับจำนวน <tbody> ในตาราง:

<!DOCTYPE html>
<html>
<style>
  body {
    color: #000;
    background: lightblue;
    height: 100vh;
    text-align: center;
  }
  table {
    margin: 2rem auto;
  }
  .show {
    font-size: 1.2rem;
  }
  .btn {
    background: #db133a;
    border: none;
    height: 2rem;
    border-radius: 2px;
    width: 40%;
    display: block;
    color: #fff;
    outline: none;
    cursor: pointer;
    margin: 1rem auto;
  }
</style>
<body>
<h1>DOM Table tBodies Collection Demo</h1>
<table border="2">
  <thead>
    <tr>
      <th>Name</th>
      <th>Roll No.</th>
    </tr>
  </thead>
  <tbody>
    <tr><td>John</td><td>071717</td></tr>
    <tr><td>Jane</td><td>031717</td></tr>
  </tbody>
  <tbody>
    <tr><td>Elon</td><td>021717</td></tr>
    <tr><td>Mario</td><td>011717</td></tr>
  </tbody>
</table>
<button onclick="get()" class="btn">Get Number of table body</button>
<div class="show"></div>
<script>
  function get() {
    var table = document.querySelector('table');
    document.querySelector('.show').innerHTML = 'Number of table body element : ' + table.tBodies.length;
  }
</script>
</body>
</html>

ผลลัพธ์ (Output)

ก่อนคลิกปุ่ม: ไม่แสดงจำนวน tbody หลังคลิกปุ่ม Get Number of table body: แสดง "Number of table body element : 2" (มี tbody 2 กลุ่มในตาราง)

โครงสร้างตาราง: ตารางสามารถมีหลาย <tbody> เพื่อจัดกลุ่มแถวข้อมูลที่เกี่ยวข้องกัน (เช่น หัวข้อต่างๆ, หน้าต่างข้อมูล)