HTML DOM의 table tBodies 컬렉션은 HTML 문서 내 테이블에 포함된 모든 <tbody> 요소들을 모아 하나의 컬렉션으로 반환하는 기능입니다. 이 컬렉션을 활용하면 자바스크립트로 테이블 본문 구조를 손쉽게 조회하고 제어할 수 있습니다.
tBodies 컬렉션 문법
tBodies 컬렉션의 기본 사용 문법은 다음과 같습니다.
object.tBodies
tBodies 컬렉션의 주요 속성
tBodies 컬렉션에서 사용할 수 있는 속성은 아래와 같습니다.
| 속성 | 설명 |
|---|---|
| length | 컬렉션에 포함된 <tbody> 요소의 개수를 반환합니다. |
tBodies 컬렉션의 주요 메서드
컬렉션 내 특정 <tbody> 요소에 접근할 때는 다음 메서드들을 활용할 수 있습니다.
| 메서드 | 설명 |
|---|---|
| [index] | 지정한 인덱스 위치의 <tbody> 요소를 컬렉션에서 반환합니다. |
| item(index) | 지정한 인덱스 위치의 <tbody> 요소를 컬렉션에서 반환합니다. |
| namedItem(id) | 지정한 id 값과 일치하는 <tbody> 요소를 컬렉션에서 반환합니다. |
이제 HTML DOM table tBodies 컬렉션의 실제 동작 예제를 살펴보겠습니다.
예제 코드
<!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>실행 결과

페이지 하단의 “Get Number of table body” 버튼을 클릭하면, 자바스크립트가 table.tBodies.length를 호출하여 해당 테이블에 포함된 <tbody> 요소의 개수를 화면에 출력합니다.

위 예제에서는 두 개의 <tbody> 블록이 존재하므로, 버튼 클릭 시 결과 영역에 “Number of table body element : 2”라는 값이 표시됩니다. 이처럼 tBodies 컬렉션은 테이블 데이터 그룹을 동적으로 확인하거나 조작해야 하는 상황에서 매우 유용하게 활용됩니다.