Access Document Title Property
In this step, you'll learn how to access the document title property using JavaScript. We'll build upon the HTML file created in the previous step and demonstrate how to retrieve and manipulate the document's title.
Create a new file called script.js
in the ~/project
directory using the WebIDE. Add the following JavaScript code:
// 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);
Now, update the index.html
file to include the JavaScript file:
<!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>
When you open this HTML file in a browser, you'll see the following behaviors:
Example output in browser console:
Document Title: DOM Properties Exploration
When you click the "Change Title" button:
New Document Title: Updated DOM Properties Lab
Key concepts demonstrated:
document.title
property retrieves the current page title
- You can dynamically change the document title using JavaScript
- The title appears in the browser tab and can be modified at runtime