HTML DOM Figcaption 객체란?
HTML DOM Figcaption 객체는 HTML5의 <figcaption> 요소를 JavaScript에서 다룰 수 있게 해주는 인터페이스입니다. <figure> 요소 내부에 위치하는 캡션을 동적으로 생성하거나 조작할 때 활용됩니다.
새로운 figcaption 요소를 만들 때는 createElement() 메서드를, 이미 문서에 존재하는 요소에 접근할 때는 getElementById() 메서드를 사용합니다.
문법(Syntax)
Figcaption 객체를 생성하는 기본 문법은 다음과 같습니다.
var p = document.createElement("FIGCAPTION");
예제
버튼을 클릭하면 이미지 아래에 캡션이 자동으로 추가되는 간단한 예제를 살펴보겠습니다.
<!DOCTYPE html>
<html>
<head>
<script>
function createCaption() {
var caption = document.createElement("FIGCAPTION");
var txt = document.createTextNode("Learn Java Servlets");
caption.appendChild(txt);
var f=document.getElementById("Figure1");
f.appendChild(caption);
}
</script>
</head>
<body>
<h2>Caption</h2>
<p>Create a caption for the below image by clicking the below button</p>
<button onclick="createCaption()">CREATE</button>
<figure id="Figure1">
<img src="https://www.tutorialspoint.com/servlets/images/servlets-mini-logo.jpg"
alt="Servlets" width="250" height="200">
</figure>
</body>
</html>
실행 결과
위 코드를 실행하면 다음과 같은 화면이 출력됩니다.

CREATE 버튼을 클릭하면 figure 요소 하단에 캡션이 추가된 모습을 확인할 수 있습니다.

코드 상세 분석
먼저 id가 "Figure1"인 figure 요소를 정의하고, 그 안에 img 요소를 포함시켰습니다.
<figure id="Figure1"> <img src="EiffelTower.jpg" alt="Eiffel Tower" width="250" height="200"> </figure>
그다음, 사용자가 클릭하면 createCaption() 함수를 실행하는 CREATE 버튼을 배치했습니다.
<button onclick="createCaption()">CREATE</button>
createCaption() 함수는 다음 순서로 동작합니다.
- figcaption 요소 생성: document 객체의 createElement() 메서드를 사용해 새로운 FIGCAPTION 요소를 만듭니다.
- 텍스트 노드 생성 및 추가: createTextNode() 메서드로 캡션에 들어갈 텍스트 노드를 생성한 뒤, appendChild() 메서드로 figcaption 요소에 붙입니다.
- figure에 캡션 삽입: getElementById() 메서드로 figure 요소를 가져온 후, appendChild()를 사용해 텍스트 노드가 포함된 figcaption을 자식 요소로 추가합니다.
function createCaption() {
var caption = document.createElement("FIGCAPTION");
var txt = document.createTextNode("Learn Java Servlets");
caption.appendChild(txt);
var f=document.getElementById("Figure1");
f.appendChild(caption);
}