HTML DOM의 createCaption() 메서드는 HTML 문서 내 테이블에 빈 <caption> 요소를 생성하여 추가하는 기능을 제공합니다. 이 메서드를 활용하면 자바스크립트만으로도 동적으로 테이블 캡션(제목)을 만들 수 있습니다.
문법(Syntax)
createCaption() 메서드의 기본 문법은 다음과 같습니다.
object.createCaption()
이 메서드는 별도의 매개변수를 받지 않으며, 호출 시 해당 테이블에 새로운 캡션 요소가 추가됩니다. 만약 테이블에 이미 캡션이 존재한다면, 기존 캡션을 그대로 반환합니다.
예제(Example)
아래 예제는 버튼을 클릭하면 createCaption() 메서드를 호출하여 테이블에 캡션을 동적으로 추가하는 방법을 보여줍니다.
<!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 createCaption() 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 Caption</button>
<script>
function create() {
var tableCaption = document.querySelector('table').createCaption();
tableCaption.innerHTML = "Student Data";
}
</script>
</body>
</html>실행 결과(Output)
위 코드를 실행하면 학생 명단이 담긴 테이블과 'Create Caption' 버튼이 화면에 표시됩니다.

'Create Caption' 버튼을 클릭하면 createCaption() 메서드가 실행되어 테이블 상단에 'Student Data'라는 캡션이 동적으로 생성되는 것을 확인할 수 있습니다.

핵심 포인트 정리
- createCaption()은 테이블 객체에서 직접 호출할 수 있는 DOM 메서드입니다.
- 빈 <caption> 요소를 생성한 후 innerHTML 등으로 원하는 텍스트를 삽입합니다.
- 캡션이 이미 존재하는 경우 중복 생성 없이 기존 캡션을 반환합니다.