document.title 속성 접근
이 단계에서는 JavaScript 를 사용하여 문서 제목 속성에 접근하는 방법을 배웁니다. 이전 단계에서 생성한 HTML 파일을 기반으로 문서의 제목을 검색하고 조작하는 방법을 시연합니다.
WebIDE 를 사용하여 ~/project 디렉토리에 script.js라는 새 파일을 생성합니다. 다음 JavaScript 코드를 추가합니다.
// Access the document title
console.log("Document Title:", document.title);
// Modify the document title
function changeTitle() {
document.title = "Updated DOM Properties Lab";
console.log("New Document Title:", document.title);
}
// Add a button to demonstrate title change
const button = document.createElement("button");
button.textContent = "Change Title";
button.onclick = changeTitle;
document.body.appendChild(button);
이제 index.html 파일을 업데이트하여 JavaScript 파일을 포함합니다.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>DOM Properties Exploration</title>
</head>
<body>
<h1>Welcome to DOM Properties Lab</h1>
<p>This page will help us explore JavaScript DOM properties.</p>
<img src="https://example.com/sample-image.jpg" alt="Sample Image" />
<img src="https://example.com/another-image.jpg" alt="Another Image" />
<script src="script.js"></script>
</body>
</html>
이 HTML 파일을 브라우저에서 열면 다음과 같은 동작을 볼 수 있습니다.
브라우저 콘솔의 예시 출력:
Document Title: DOM Properties Exploration
"Change Title" 버튼을 클릭하면:
New Document Title: Updated DOM Properties Lab
시연된 주요 개념:
document.title 속성은 현재 페이지 제목을 검색합니다.
- JavaScript 를 사용하여 문서 제목을 동적으로 변경할 수 있습니다.
- 제목은 브라우저 탭에 나타나며 런타임에 수정할 수 있습니다.