ドキュメントのタイトルプロパティにアクセスする
このステップでは、JavaScriptを使ってドキュメントのタイトルプロパティにアクセスする方法を学びます。前のステップで作成したHTMLファイルを基に、ドキュメントのタイトルを取得して操作する方法を示します。
WebIDEを使って ~/project
ディレクトリに script.js
という新しいファイルを作成します。以下のJavaScriptコードを追加します。
// ドキュメントのタイトルにアクセスする
console.log("Document Title:", document.title);
// ドキュメントのタイトルを変更する
function changeTitle() {
document.title = "Updated DOM Properties Lab";
console.log("New Document Title:", document.title);
}
// タイトルの変更を示すボタンを追加する
const button = document.createElement("button");
button.textContent = "Change Title";
button.onclick = changeTitle;
document.body.appendChild(button);
次に、JavaScriptファイルを含めるように index.html
ファイルを更新します。
<!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を使ってドキュメントのタイトルを動的に変更できます
- タイトルはブラウザのタブに表示され、実行時に変更できます