deleteRow() 메서드란?
HTML DOM의 deleteRow() 메서드는 HTML 문서 내 테이블에서 지정한 위치의 <tr> 요소(행)를 삭제하는 데 사용됩니다. 자바스크립트만으로 동적으로 테이블의 행을 제거할 수 있어, 사용자 입력에 따라 데이터 목록을 갱신하는 웹 애플리케이션에서 유용하게 활용됩니다.
구문(Syntax)
object.deleteRow(index)
여기서 index는 삭제할 행의 위치를 나타내는 숫자입니다.
- 인덱스는 0부터 시작합니다. 즉, 첫 번째 행은 0, 두 번째 행은 1로 지정합니다.
- index를 생략하거나 -1을 전달하면 마지막 행이 삭제됩니다.
예제(Example)
다음은 HTML DOM 테이블 deleteRow() 메서드를 활용한 예제입니다.
<!DOCTYPE html>
<html>
<style>
body {
color: #000;
background: lightblue;
height: 100vh;
text-align: center;
}
table {
margin: 2rem auto;
}
.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;
}
</style>
<body>
<h1>DOM Table deleteRow() Method 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="remove()" class="btn">Remove Row</button>
<script>
function remove() {
var tableFooter = document.querySelector('table').deleteRow(1);
}
</script>
</body>
</html>실행 결과(Output)

위 화면에서 "Remove Row" 버튼을 클릭해 보세요.

버튼을 클릭하면 deleteRow(1)에 의해 인덱스 1번 위치(두 번째 행)에 해당하는 'Jane' 행이 테이블에서 삭제된 것을 확인할 수 있습니다.
참고 사항
- 삭제하려는 인덱스가 존재하지 않으면 IndexSizeError 오류가 발생하므로, 실행 전 테이블의 행 개수(
table.rows.length)를 확인하는 것이 안전합니다. - 행을 추가할 때는 반대 기능을 하는
insertRow()메서드를 사용할 수 있습니다.