Explore DOM Properties in JavaScript

CSSCSSBeginner
Practice Now

Introduction

In this lab, participants will explore the Document Object Model (DOM) properties in JavaScript by creating an interactive HTML document and using JavaScript to access and manipulate various document attributes. The lab provides a hands-on approach to understanding key DOM properties such as document title, URL, links, images, and body content.

Through a step-by-step process, learners will first create a basic HTML structure, then progressively use JavaScript to interact with different document properties. By examining methods like accessing the document title, retrieving URLs and links, counting images, and exploring document body and cookie properties, participants will gain practical insights into how JavaScript can dynamically interact with web page elements and metadata.

Create HTML Document with Basic Structure

In this step, you'll learn how to create a basic HTML document that will serve as the foundation for exploring DOM properties in JavaScript. We'll use the WebIDE to create an HTML file with a simple structure that includes essential elements.

First, navigate to the ~/project directory in the WebIDE. Create a new file called index.html by right-clicking in the file explorer and selecting "New File".

Copy and paste the following HTML code into the index.html 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" />
  </body>
</html>

Let's break down the key components of this HTML document:

  • <!DOCTYPE html> declares this as an HTML5 document
  • <html lang="en"> sets the language of the document
  • <head> contains metadata about the document
  • <title> sets the page title, which we'll use in later steps
  • <body> contains the visible content of the page
  • We've included two <img> tags to demonstrate image-related DOM properties in subsequent steps

Example output when you open this file in a browser:

[A webpage with the title "DOM Properties Exploration"
 displaying "Welcome to DOM Properties Lab"
 and "This page will help us explore JavaScript DOM properties."]

This simple HTML structure provides the perfect starting point for our DOM properties exploration lab.

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

In this step, you'll learn how to access the document's URL and retrieve information about links using JavaScript DOM properties. We'll update the script.js file to demonstrate these capabilities.

Open the script.js file in the WebIDE and add the following code:

// Retrieve and display the current document URL
console.log("Current Document URL:", document.URL);

// Get the number of links on the page
const linkCount = document.links.length;
console.log("Total Number of Links:", linkCount);

// Display information about all links
function displayLinkInfo() {
  const links = document.links;
  console.log("Link Information:");
  for (let i = 0; i < links.length; i++) {
    console.log(`Link ${i + 1}:`);
    console.log(`  Href: ${links[i].href}`);
    console.log(`  Text: ${links[i].text}`);
  }
}

// Add a button to show link information
const linkButton = document.createElement("button");
linkButton.textContent = "Show Link Details";
linkButton.onclick = displayLinkInfo;
document.body.appendChild(linkButton);

Update the index.html file to include some additional links:

<!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>

    <div>
      <a href="https://example.com">Example Website</a>
      <a href="https://labex.io">LabEx Learning Platform</a>
    </div>

    <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>

Example output in browser console:

Current Document URL: file:///home/labex/project/index.html
Total Number of Links: 2

Link Information:
Link 1:
  Href: https://example.com
  Text: Example Website
Link 2:
  Href: https://labex.io
  Text: LabEx Learning Platform

Key concepts demonstrated:

  • document.URL retrieves the full URL of the current document
  • document.links provides a collection of all links on the page
  • You can iterate through links and access their properties like href and text

Count and Display Images on Page

In this step, you'll learn how to count and display information about images on a web page using JavaScript DOM properties. We'll update the script.js file to explore image-related functionality.

Open the script.js file in the WebIDE and add the following code:

// Count the number of images on the page
const imageCount = document.images.length;
console.log("Total Number of Images:", imageCount);

// Function to display image details
function displayImageInfo() {
  const images = document.images;
  console.log("Image Information:");
  for (let i = 0; i < images.length; i++) {
    console.log(`Image ${i + 1}:`);
    console.log(`  Source: ${images[i].src}`);
    console.log(`  Alt Text: ${images[i].alt}`);
  }
}

// Create a button to show image details
const imageButton = document.createElement("button");
imageButton.textContent = "Show Image Details";
imageButton.onclick = displayImageInfo;
document.body.appendChild(imageButton);

// Add a simple image information display area
const infoDiv = document.createElement("div");
infoDiv.id = "image-info";
document.body.appendChild(infoDiv);

// Update the div with image count
infoDiv.textContent = `Number of Images: ${imageCount}`;

Update the index.html file to include more images with different attributes:

<!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>

    <div>
      <a href="https://example.com">Example Website</a>
      <a href="https://labex.io">LabEx Learning Platform</a>
    </div>

    <div id="image-container">
      <img src="https://example.com/sample-image.jpg" alt="Sample Image" />
      <img src="https://example.com/another-image.jpg" alt="Another Image" />
      <img src="https://example.com/third-image.png" alt="Third Image" />
    </div>

    <script src="script.js"></script>
  </body>
</html>

Example output in browser console:

Total Number of Images: 3
Image Information:
Image 1:
  Source: https://example.com/sample-image.jpg
  Alt Text: Sample Image
Image 2:
  Source: https://example.com/another-image.jpg
  Alt Text: Another Image
Image 3:
  Source: https://example.com/third-image.png
  Alt Text: Third Image

Key concepts demonstrated:

  • document.images provides a collection of all images on the page
  • You can access image properties like src and alt
  • Dynamically create and manipulate page elements using JavaScript

In this step, you'll explore the document body and cookie properties in JavaScript, learning how to manipulate page content and work with browser cookies.

Open the script.js file in the WebIDE and add the following code:

// Demonstrate document body manipulation
function modifyBodyContent() {
  // Access and modify document body
  const body = document.body;
  console.log("Original Body Inner HTML:", body.innerHTML);

  // Create a new paragraph element
  const newParagraph = document.createElement("p");
  newParagraph.textContent =
    "This paragraph was dynamically added to the body!";
  body.appendChild(newParagraph);

  console.log("Updated Body Inner HTML:", body.innerHTML);
}

// Demonstrate cookie properties
function manageCookies() {
  // Set a new cookie
  document.cookie =
    "labExperience=JavaScript DOM; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";

  // Display all cookies
  console.log("Current Cookies:", document.cookie);

  // Create a button to show cookies
  const cookieButton = document.createElement("button");
  cookieButton.textContent = "Show Cookies";
  cookieButton.onclick = () => {
    alert(`Cookies: ${document.cookie}`);
  };
  document.body.appendChild(cookieButton);
}

// Create buttons to trigger demonstrations
const bodyButton = document.createElement("button");
bodyButton.textContent = "Modify Body Content";
bodyButton.onclick = modifyBodyContent;
document.body.appendChild(bodyButton);

const cookieButton = document.createElement("button");
cookieButton.textContent = "Manage Cookies";
cookieButton.onclick = manageCookies;
document.body.appendChild(cookieButton);

Update the index.html file to ensure compatibility:

<!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>

    <div>
      <a href="https://example.com">Example Website</a>
      <a href="https://labex.io">LabEx Learning Platform</a>
    </div>

    <div id="image-container">
      <img src="https://example.com/sample-image.jpg" alt="Sample Image" />
      <img src="https://example.com/another-image.jpg" alt="Another Image" />
      <img src="https://example.com/third-image.png" alt="Third Image" />
    </div>

    <script src="script.js"></script>
  </body>
</html>

Example output in browser console:

// After clicking "Modify Body Content"
Original Body Inner HTML: [initial HTML content]
Updated Body Inner HTML: [HTML content with new paragraph added]

// After clicking "Manage Cookies"
Current Cookies: labExperience=JavaScript DOM

Key concepts demonstrated:

  • Accessing and modifying document.body
  • Creating and appending new elements dynamically
  • Setting and reading browser cookies
  • Interacting with document properties using JavaScript

Summary

In this lab, participants learn how to explore Document Object Model (DOM) properties using JavaScript by creating a structured HTML document and implementing various property access techniques. The lab begins with constructing a basic HTML file that includes essential elements like title, body, and images, serving as a foundation for understanding DOM interactions.

The practical exercise guides learners through accessing different document properties such as title, URL, links, and image count, demonstrating how JavaScript can dynamically retrieve and manipulate web page metadata. By working through these steps, participants gain hands-on experience in examining and interacting with fundamental DOM properties, enhancing their understanding of client-side web development techniques.