HTML DOM의 Title text 속성은 문서 내 <title> 요소의 텍스트 값을 가져오거나 설정하는 데 사용됩니다. 이 속성을 활용하면 브라우저 탭에 표시되는 문서 제목을 자바스크립트로 동적으로 읽어오거나 변경할 수 있습니다.
문법(Syntax)
text 속성의 기본적인 사용 방법은 다음과 같습니다.
문자열 값 반환
titleElementObject.text
문자열 값 설정
titleElementObject.text = string
예제(Example)
다음은 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>
실행 결과(Output)
'What's the title of document?' 버튼을 클릭하기 전 −

'What's the title of document?' 버튼을 클릭한 후 −

위 예제에서 볼 수 있듯이 text 속성은 단순히 제목을 읽어오는 것뿐만 아니라, 반환된 문자열을 가공하여 다른 요소에 활용하는 등 다양하게 응용할 수 있습니다.