HTML DOM Title 객체란?
HTML DOM의 Title 객체는 HTML 문서의 <title> 요소를 나타냅니다. 이 객체를 활용하면 브라우저 탭에 표시되는 문서 제목을 JavaScript로 동적으로 읽거나 변경할 수 있습니다.
<title> 요소 생성하기
createElement() 메서드를 호출하여 새로운 <title> 요소를 만들 수 있습니다.
var titleObject = document.createElement("TITLE")
Title 객체의 주요 속성
생성된 titleObject는 다음과 같은 속성을 제공합니다.
| 속성 | 설명 |
|---|---|
| text | 문서의 <title> 요소 값을 설정하거나 반환합니다. |
그럼 Title text 속성을 실제로 활용하는 예제를 살펴보겠습니다.
예제
아래 예제에서는 버튼을 클릭하면 현재 문서의 제목을 화면에 출력하고, legend 영역에는 제목에 포함된 공백을 하이픈(-)으로 바꿔 표시합니다.
<!DOCTYPE html>
<html>
<head>
<title id="titleSelect">HTML DOM Title text</title>
<style>
form {
width:70%;
margin: 0 auto;
text-align: center;
}
* {
padding: 2px;
margin:5px;
}
input[type="button"] {
border-radius: 10px;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend id="legendSelect"></legend>
<input type="button" onclick="getTitleText()" value="What's the title of document?">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var legendSelect = document.getElementById("legendSelect");
var titleSelect = document.getElementById("titleSelect");
function getTitleText() {
divDisplay.textContent = 'Title of document: '+titleSelect.text;
legendSelect.textContent = titleSelect.text.split(' ').join('-');
}
</script>
</body>
</html>
출력 결과
'What's the title of document?' 버튼을 클릭하기 전의 화면입니다.

버튼을 클릭하면 문서의 제목이 div 영역에 그대로 표시되고, legend에는 공백이 하이픈(-)으로 대체된 제목이 나타납니다.
