HTML DOM의 table rows 컬렉션은 HTML 문서 내 테이블에 포함된 모든 <tr> 요소를 하나의 컬렉션으로 반환하는 기능입니다. 이를 활용하면 테이블의 행 개수를 확인하거나 특정 행에 접근하는 등 동적인 작업을 손쉽게 처리할 수 있습니다.
문법(Syntax)
rows 컬렉션의 기본 문법은 다음과 같습니다.
object.rows
rows 컬렉션의 속성(Properties)
rows 컬렉션에서 제공하는 주요 속성은 다음과 같습니다.
| 속성 | 설명 |
|---|---|
| length | 컬렉션에 포함된 <tr> 요소의 총 개수를 반환합니다. |
rows 컬렉션의 메서드(Methods)
rows 컬렉션에서는 아래와 같은 메서드를 통해 특정 행 요소에 접근할 수 있습니다.
| 메서드 | 설명 |
|---|---|
| [index] | 지정한 인덱스 위치의 <tr> 요소를 컬렉션에서 반환합니다. |
| item(index) | 지정한 인덱스 위치의 <tr> 요소를 컬렉션에서 반환합니다. |
| namedItem(id) | 지정한 id 값을 가진 <tr> 요소를 컬렉션에서 반환합니다. |
이제 HTML DOM table rows 컬렉션의 실제 사용 예제를 살펴보겠습니다.
예제(Example)
<!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 rows 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>
</table>
<button onclick="get()" class="btn">Get Number of Rows</button>
<div class="show"></div>
<script>
function get() {
var table = document.querySelector('table');
document.querySelector('.show').innerHTML = 'Number of rows : ' + table.rows.length;
}
</script>
</body>
</html>실행 결과(Output)

위 화면에서 “Get Number of Rows” 버튼을 클릭하면, 컬렉션에 포함된 <tr> 요소의 개수가 화면에 표시됩니다.

이처럼 table.rows.length를 활용하면 테이블의 전체 행 개수를 간단하게 구할 수 있으며, 인덱스나 id를 이용해 특정 행에도 쉽게 접근할 수 있습니다.