探索 JavaScript 中的 DOM 属性

CSSCSSBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,参与者将通过创建一个交互式 HTML 文档并使用 JavaScript 访问和操作各种文档属性,来探索 JavaScript 中的文档对象模型(DOM)属性。实验采用动手实践的方式,帮助学习者理解关键的 DOM 属性,如文档标题、URL、链接、图片和正文内容。

通过逐步的过程,学习者将首先创建一个基本的 HTML 结构,然后逐步使用 JavaScript 与不同的文档属性进行交互。通过探索访问文档标题、获取 URL 和链接、统计图片数量以及研究文档正文和 cookie 属性等方法,参与者将深入了解 JavaScript 如何动态地与网页元素和元数据进行交互。

创建具有基本结构的 HTML 文档

在这一步中,你将学习如何创建一个基本的 HTML 文档,作为探索 JavaScript 中 DOM 属性的基础。我们将使用 WebIDE 创建一个包含简单结构的 HTML 文件,其中包含一些基本元素。

首先,在 WebIDE 中导航到 ~/project 目录。右键点击文件资源管理器并选择“新建文件”,创建一个名为 index.html 的文件。

将以下 HTML 代码复制并粘贴到 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" />
  </body>
</html>

让我们分解一下这个 HTML 文档的关键组成部分:

  • <!DOCTYPE html> 声明这是一个 HTML5 文档
  • <html lang="en"> 设置文档的语言
  • <head> 包含文档的元数据
  • <title> 设置页面标题,我们将在后续步骤中使用它
  • <body> 包含页面的可见内容
  • 我们包含了两组 <img> 标签,以便在后续步骤中演示与图片相关的 DOM 属性

在浏览器中打开此文件时的示例输出:

[一个标题为 "DOM Properties Exploration" 的网页
 显示 "Welcome to DOM Properties Lab"
 和 "This page will help us explore JavaScript DOM properties."]

这个简单的 HTML 结构为我们的 DOM 属性探索实验提供了完美的起点。

访问文档标题属性

在这一步中,你将学习如何使用 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 动态更改文档标题
  • 标题显示在浏览器标签页中,并且可以在运行时修改

检索文档 URL 和链接

在这一步中,你将学习如何使用 JavaScript DOM 属性访问文档的 URL 并检索链接信息。我们将更新 script.js 文件以演示这些功能。

在 WebIDE 中打开 script.js 文件并添加以下代码:

// 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);

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

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

浏览器控制台中的示例输出:

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

演示的关键概念:

  • document.URL 用于检索当前文档的完整 URL
  • document.links 提供了页面中所有链接的集合
  • 你可以遍历链接并访问它们的属性,如 hreftext

统计并显示页面中的图片

在这一步中,你将学习如何使用 JavaScript DOM 属性统计并显示网页中图片的相关信息。我们将更新 script.js 文件以探索与图片相关的功能。

在 WebIDE 中打开 script.js 文件并添加以下代码:

// 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}`;

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

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

浏览器控制台中的示例输出:

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

演示的关键概念:

  • document.images 提供了页面中所有图片的集合
  • 你可以访问图片的属性,如 srcalt
  • 使用 JavaScript 动态创建和操作页面元素

在这一步中,你将探索 JavaScript 中的文档 body 和 cookie 属性,学习如何操作页面内容并处理浏览器 cookie。

在 WebIDE 中打开 script.js 文件并添加以下代码:

// 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);

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

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

浏览器控制台中的示例输出:

// 点击 "Modify Body Content" 后
Original Body Inner HTML: [初始 HTML 内容]
Updated Body Inner HTML: [添加了新段落的 HTML 内容]

// 点击 "Manage Cookies" 后
Current Cookies: labExperience=JavaScript DOM

演示的关键概念:

  • 访问和修改 document.body
  • 动态创建并附加新元素
  • 设置和读取浏览器 cookie
  • 使用 JavaScript 与文档属性交互

总结

在本实验中,参与者通过创建一个结构化的 HTML 文档并实现各种属性访问技术,学习如何使用 JavaScript 探索文档对象模型(DOM)属性。实验从构建一个包含标题、正文和图片等基本元素的 HTML 文件开始,为理解 DOM 交互奠定基础。

实践练习引导学习者访问不同的文档属性,如标题、URL、链接和图片数量,展示 JavaScript 如何动态检索和操作网页元数据。通过完成这些步骤,参与者能够获得检查和与基本 DOM 属性交互的实践经验,从而加深对客户端 Web 开发技术的理解。