HTML DOM의 table createTHead() 메서드는 HTML 문서 내 테이블에 빈 <thead> 요소를 생성하여 추가하는 기능을 합니다.
테이블에 이미 <thead> 요소가 존재하는 경우, 새로운 헤더를 만들지 않고 기존 <thead> 요소를 그대로 반환한다는 점도 함께 기억해 두면 좋습니다.
구문(Syntax)
createTHead() 메서드의 기본 구문은 다음과 같습니다.
object.createTHead()
메서드는 매개변수 없이 호출하며, 실행 결과로 새로 생성된(또는 기존에 존재하는) <thead> 요소 객체를 반환합니다.
예제(Example)
HTML DOM table createTHead() 메서드가 실제로 어떻게 동작하는지 예제를 통해 확인해 보겠습니다.
<!DOCTYPE html>
<html>
<style>
body {
color: #000;
background: lightblue;
height: 100vh;
text-align: center;
}
table {
margin: 2rem auto;
}
caption {
color: #db133a;
}
.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 createTHead() Method Demo</h1>
<table border="2">
<tr>
<td>Name</td>
<td>Roll No.</td>
</tr>
<tr>
<td>John</td>
<td>071717</td>
</tr>
<tr>
<td>Jane</td>
<td>031717</td>
</tr>
</table>
<button onclick="create()" class="btn">Create Header</button>
<script>
function create() {
var tableHeader = document.querySelector('table').createTHead();
tableHeader.innerHTML = "Table Heading";
}
</script>
</body>
</html>실행 결과(Output)
위 코드를 브라우저에서 실행하면 아래와 같은 화면이 나타납니다.

이제 “Create Header” 버튼을 클릭하면, JavaScript의 createTHead() 메서드가 실행되어 테이블에 새로운 헤더(<thead>)가 동적으로 추가됩니다.

코드 살펴보기
핵심 로직은 다음 두 줄입니다.
- document.querySelector('table'): 문서에서 첫 번째 테이블 요소를 선택합니다.
- createTHead(): 해당 테이블에 빈 <thead> 요소를 생성하고 반환합니다.
- innerHTML: 생성된 헤더 안에 "Table Heading"이라는 텍스트를 삽입합니다.
이처럼 createTHead() 메서드를 활용하면 사용자의 클릭 이벤트 등 특정 상황에 맞춰 테이블 헤더를 손쉽게 동적 제어할 수 있습니다.