JavaScript 文档对象详解:DOM 属性、方法与实用示例

目次

1. 引言

JavaScript 是 Web 开发中一种必不可少的编程语言。在其核心功能中,document 对象 在控制和操作网页结构和内容方面发挥着核心作用。本文将以初学者到中级用户都能理解的方式介绍 JavaScript 的 document 对象。

JavaScript 的用途是什么?

JavaScript 是一种与 HTML 和 CSS 一起使用的编程语言,主要用于在网页上创建动态行为和用户交互。例如,包括表单输入验证、显示弹出菜单以及添加动画效果。

特别是,document 对象 提供了使用 JavaScript 访问和编辑网页元素的功能。使用此对象,您可以选择 HTML 元素、添加新元素、设置事件并执行许多其他操作。

为什么需要学习 document 对象?

document 对象作为 DOM (Document Object Model) 的一部分起作用。DOM 是一种模型,它以可编程方式表示 HTML 或 XML 文档的结构,并且它是 Web 开发的基本必备知识。

通过理解这个模型并学习如何有效使用 document 对象,您可以处理以下情况:

  • 动态更新用户界面
  • 实时表单验证
  • 异步数据加载和渲染 (AJAX 或 Fetch API)
  • 实现模态窗口和弹出菜单

本文将学习什么

本文以有组织的方式解释了 document 对象从基础到更高级的用法,使用实际代码示例来展示其工作原理。阅读后,您将能够理解以下内容:

  • document 对象的基本结构和功能
  • 如何选择和操作 HTML 元素
  • 如何设置事件监听器以及实际用法示例
  • 重要的注意事项和最佳实践

初学者可以牢固掌握基础知识,而中级用户可以获得编写更高效代码的提示。

2. JavaScript document 对象是什么?

在 JavaScript 中,document 对象 是处理网页的最重要接口之一。作为 DOM (Document Object Model) 的一部分提供,它允许您轻松操作和修改网页内的元素。

document 对象的作用

document 对象表示浏览器加载的整个 HTML 文档。这使您能够使用 JavaScript 以编程方式控制 HTML 结构、样式和内容。

例如,您可以执行以下操作:

  • 选择和编辑 HTML 元素
  • 创建并附加新元素
  • 更改页面背景颜色或文本内容
  • 通过设置事件监听器检测用户操作

DOM 与 document 对象之间的关系

DOM (Document Object Model) 将 HTML 或 XML 文档表示为树结构。在该树的顶部是 document 对象。

下面的图表显示了 DOM 与 document 对象之间关系的简单视图。

document
├── html
│   ├── head
│   │   └── title
│   └── body
│       ├── div
│       ├── p
│       └── button

通过这种方式,document 对象将整个页面表示为树,并作为访问每个元素的起点。

document 对象的基本用法

让我们看一些使用 document 对象简单的示例。

示例 1:获取页面标题

console.log(document.title); // Get the page title

示例 2:更改背景颜色

document.body.style.backgroundColor = "lightblue";

示例 3:选择和编辑元素

let heading = document.getElementById("main-title");
heading.textContent = "New Title";

通过结合这些操作,您可以构建交互式和动态的网页。

document 对象的关键特性

  1. 实时更新 – 对文档的更改会立即反映。
  2. 访问层次结构 – 您可以通过遍历 DOM 树灵活地选择和修改元素。
  3. 事件管理 – 您可以根据用户操作添加事件监听器。

3. document 对象的关键属性和方法

JavaScript 的 document 对象提供了许多属性和方法,支持广泛的网页操作。本节将介绍常用的属性和方法。

1. 常用属性

下面列出了 document 对象的常用属性以及它们的用途。

PropertyDescriptionExample
document.titleGets or sets the current page title.console.log(document.title);
document.URLGets the URL of the current page.console.log(document.URL);
document.bodyGets the page’s <body> element.document.body.style.backgroundColor = "yellow";
document.headGets the page’s <head> element.console.log(document.head.innerHTML);
document.formsGets all form elements on the page.console.log(document.forms[0]);
document.imagesGets all image elements on the page.console.log(document.images);
document.linksGets all link elements on the page.console.log(document.links);
document.cookieGets or sets cookie information for the page.console.log(document.cookie);
document.documentElementGets the <html> element representing the entire page.console.log(document.documentElement);

这些属性帮助您轻松获取和更新网页信息。

2. 常用方法

接下来是用于操作元素和添加新元素的方法。

MethodDescriptionExample
getElementById(id)Selects an element with the specified ID attribute.let element = document.getElementById("header");
getElementsByClassName(class)Selects all elements with the specified class name (returned as an HTMLCollection).let items = document.getElementsByClassName("item");
getElementsByTagName(tag)Selects all elements with the specified tag name.let paragraphs = document.getElementsByTagName("p");
querySelector(selector)Selects the first element that matches the CSS selector.let firstDiv = document.querySelector("div.container");
querySelectorAll(selector)Selects all elements that match the CSS selector (returned as a NodeList).let allDivs = document.querySelectorAll("div.container");
createElement(tag)Creates a new HTML element.let newDiv = document.createElement("div");
appendChild(node)Adds a new child node to the specified element.document.body.appendChild(newDiv);
removeChild(node)Removes the specified child node.document.body.removeChild(newDiv);
write(content)Writes HTML or text directly into the document (deprecated).document.write("<h1>Hello World!</h1>");
addEventListener(event, func)Adds an event listener to an element for a specified event.document.addEventListener("click", () => { alert("Clicked!"); });

3. 结合属性和方法的示例

让我们来看一些实际使用的示例。

示例 1:获取表单值

let form = document.forms[0];
let input = form.elements["username"];
console.log(input.value);

示例 2:创建并追加新元素

let newParagraph = document.createElement("p");
newParagraph.textContent = "This is a new paragraph.";
document.body.appendChild(newParagraph);

示例 3:添加点击事件

document.getElementById("myButton").addEventListener("click", () => {
    alert("The button was clicked!");
});

4. 小结

document 对象提供了一套丰富的属性和方法,可用于操作网页。掌握它们后,您可以创建更具交互性和功能性的网页。

4. 选择和操作 HTML 元素(附代码示例)

通过使用 JavaScript 的 document 对象,您可以轻松选择 HTML 元素、编辑其内容并更改属性。本节将详细说明常见的选择和操作技巧,并提供代码示例。

1. 如何选择 HTML 元素

1-1. 通过 ID 选择 – getElementById()

使用 HTML 元素上设置的 ID 属性来选择元素。

示例:更改元素文本
HTML:

<h1 id="title">Original Title</h1>

JavaScript:

let title = document.getElementById("title");
title.textContent = "New Title"; // Change the text

关键点

  • ID 必须唯一。不能将相同的 ID 分配给多个元素。

1-2. 通过类名选择 – getElementsByClassName()

选择具有相同类名的多个元素。

示例:更改背景颜色
HTML:

<div class="box">Box 1</div>
<div class="box">Box 2</div>

JavaScript:

let boxes = document.getElementsByClassName("box");
for (let i = 0; i < boxes.length; i++) {
    boxes[i].style.backgroundColor = "lightblue";
}

关键点

  • 您可以像遍历数组一样遍历这些元素,并逐个进行操作。

1-3. 通过标签名选择 – getElementsByTagName()

选择所有具有指定标签名的元素。

示例:更改所有段落的颜色
HTML:

<p>Paragraph 1</p>
<p>Paragraph 2</p>

JavaScript:

let paragraphs = document.getElementsByTagName("p");
for (let p of paragraphs) {
    p.style.color = "green";
}

1-4. 使用 CSS 选择器 – querySelector()querySelectorAll()

使用 CSS 选择器可以更灵活地选择元素。

选择单个元素 – querySelector()

let firstDiv = document.querySelector("div.box");
firstDiv.textContent = "Selected box";

选择多个元素 – querySelectorAll()

let allDivs = document.querySelectorAll("div.box");
allDivs.forEach(div => div.style.border = "1px solid red");

2. 如何操作 HTML 元素

2-1. 编辑文本或 HTML

.示例:innerHTMLtextContent 的区别
HTML:

<div id="content">Original text</div>

JavaScript:

let content = document.getElementById("content");

// Change text only
content.textContent = "<b>New text</b>"; // Displayed as plain text

// Change including HTML
content.innerHTML = "<b>New text</b>"; // Displayed in bold

关键点

  • textContent 将标签视为普通字符串,不会将其解释为 HTML。
  • innerHTML 直接应用 HTML,但必须注意安全(防止 XSS)。

2-2. 编辑属性

示例:更改链接
HTML:

<a id="link" href="https://example.com">Original link</a>

JavaScript:

let link = document.getElementById("link");
link.setAttribute("href", "https://google.com"); // Change the URL
link.textContent = "Link to Google";             // Change the label

2-3. 创建并追加新元素

示例:添加新列表项
HTML:

<ul id="list">
  <li>Item 1</li>
</ul>

JavaScript:

let list = document.getElementById("list");
let newItem = document.createElement("li");
newItem.textContent = "Item 2"; // Create a new item
list.appendChild(newItem);      // Append to the end of the list

2-4. 删除元素

示例:点击按钮时删除元素
HTML:

<div id="box">Element to be removed</div>
<button id="deleteBtn">Remove</button>

JavaScript:

let box = document.getElementById("box");
let deleteBtn = document.getElementById("deleteBtn");

deleteBtn.addEventListener("click", () => {
    box.remove(); // Remove the element
});

3. 小结

在本节中,您学习了如何通过实际示例使用 document 对象选择和操作 HTML 元素。掌握这些技术可以更轻松地实现网页的动态控制。

5. 创建并追加新元素的步骤(含图示)

使用 JavaScript 的 document 对象,您可以动态创建新的 HTML 元素并将其追加到现有页面中。本节我们通过代码示例和图示说明创建和追加元素的具体步骤。

1. 如何创建新元素

1-1. 创建元素 – createElement()

使用 document.createElement() 方法创建一个新的 HTML 元素。

示例:创建一个新的段落元素

let newParagraph = document.createElement("p"); // Create a new <p> element
newParagraph.textContent = "This paragraph was added dynamically."; // Set the text

关键点

  • 创建的元素尚未添加到 DOM 中。
  • 您可以自由设置文本和属性。

2. 为元素设置属性和样式

2-1. 设置属性 – setAttribute()

要为创建的元素设置属性,请使用 setAttribute() 方法。

示例:为链接元素添加属性

let link = document.createElement("a");
link.textContent = "Google";
link.setAttribute("href", "https://google.com"); // Set the URL
link.setAttribute("target", "_blank");           // Open in a new tab

2-2. 设置样式 – style 属性

如果想直接设置样式,请使用 style 属性。

示例:为按钮设置样式

let button = document.createElement("button");
button.textContent = "Click";
button.style.backgroundColor = "blue"; // Background color
button.style.color = "white";          // Text color
button.style.padding = "10px 20px";    // Padding

3. 将元素追加到页面

您可以使用 appendChild()insertBefore() 将创建的元素追加到 DOM 中。

3-1. 追加到末尾 – appendChild()

示例:追加列表项
HTML:

<ul id="list">
  <li>Item 1</li>
</ul>

JavaScript:

let list = document.getElementById("list");
let newItem = document.createElement("li");
newItem.textContent = "Item 2"; // Create a new item
list.appendChild(newItem);      // Append to the end of the list

3-2. 在特定位置插入 – insertBefore()

示例:在指定位置插入项目

let referenceItem = list.firstElementChild; // Use the first item as a reference
list.insertBefore(newItem, referenceItem);  // Insert before the first item

4. 删除元素

您可以使用 removeChild()remove() 删除已创建的元素。

4-1. 删除子元素 – removeChild()

let itemToRemove = list.lastElementChild; // Get the last item
list.removeChild(itemToRemove);           // Remove it

4-2. 删除元素本身 – remove()

newItem.remove(); // Remove itself

5. 实践示例:动态创建卡片元素

下面是一个示例,动态创建一个新的“卡片”元素,设置样式,并将其追加到页面中。

HTML:

<div id="container"></div>

JavaScript:

let container = document.getElementById("container");

// Create the card element
let card = document.createElement("div");
card.classList.add("card"); // Add a class

// Create the card title
let title = document.createElement("h2");
title.textContent = "Card Title";

// Create the card body text
let description = document.createElement("p");
description.textContent = "This is the description text for the card.";

// Assemble and append
card.appendChild(title);
card.appendChild(description);
container.appendChild(card); // Append to the page

// Styling
card.style.border = "1px solid #ccc";
card.style.padding = "10px";
card.style.margin = "10px";
card.style.width = "200px";
card.style.boxShadow = "0 4px 6px rgba(0, 0, 0, 0.1)";

结果:

Card Title
This is the description text for the card.

6. 小结

在本节中,您学习了从创建新元素、设置属性和样式到将其追加到页面的完整工作流程。通过运用这些技术,生成动态网页内容将变得更加容易。

6. 如何设置事件监听器(实践示例)

在 JavaScript 中,您可以使用 document 对象设置事件监听器,并在用户操作时执行动态处理。本节将从事件监听器的基础知识到实际使用示例进行全面讲解。

1. 什么是事件监听器?

事件监听器是一种检测用户操作(如点击、输入或鼠标移动)并执行相应操作的机制。

示例:基础点击事件

document.getElementById("myButton").addEventListener("click", () => {
    alert("The button was clicked!");
});

2. 如何添加事件监听器

2-1. addEventListener() 的基本用法

addEventListener() 方法使用以下语法:

element.addEventListener(event, function, useCapture);

参数说明

  1. event – 事件类型(例如:clickmouseoverkeydown)。
  2. function – 要执行的函数(匿名或具名)。
  3. useCapture – 事件传播方式(捕获阶段为 true,冒泡阶段为 false)。

示例:添加 mouseover 事件

let box = document.getElementById("box");
box.addEventListener("mouseover", () => {
    box.style.backgroundColor = "lightblue";
});

3. 常用事件类型

以下是常用的事件类型及示例。

EventDescriptionExample
clickWhen an element is clickedButton click handling
dblclickWhen an element is double-clickedSelecting text
mouseoverWhen the mouse pointer enters an elementStart hover animation
mouseoutWhen the mouse pointer leaves an elementEnd hover animation
keydownWhen a key is pressedDetect keyboard input
keyupWhen a key is releasedValidate input after typing
submitWhen a form is submittedValidate form data
focusWhen an element receives focusAuto-assist input fields
blurWhen an element loses focusInput error checking

4. 实践事件监听器示例

4-1. 点击按钮更改文本

HTML:

<button id="changeText">Change</button>
<p id="text">Original text</p>

JavaScript:

let button = document.getElementById("changeText");
let text = document.getElementById("text");

button.addEventListener("click", () => {
    text.textContent = "New text";
});

4-2. Real-time input detection

HTML:

<input type="text" id="nameInput" placeholder="Enter your name">
<p id="output"></p>

JavaScript:

let input = document.getElementById("nameInput");
let output = document.getElementById("output");

input.addEventListener("input", () => {
    output.textContent = "Input: " + input.value;
});

4-3. Change background color on hover

HTML:

<div id="hoverBox" style="width: 100px; height: 100px; background-color: lightgray;"></div>

JavaScript:

let hoverBox = document.getElementById("hoverBox");

hoverBox.addEventListener("mouseover", () => {
    hoverBox.style.backgroundColor = "yellow";
});

hoverBox.addEventListener("mouseout", () => {
    hoverBox.style.backgroundColor = "lightgray";
});

5. How to remove event listeners

You can remove an event listener using the removeEventListener() method.

Example: Remove a click event

function handleClick() {
    alert("Clicked!");
}

let button = document.getElementById("myButton");
button.addEventListener("click", handleClick);

// Remove the event listener
button.removeEventListener("click", handleClick);

Important note

  • To remove an event listener, you must reference the same function. Anonymous functions cannot be removed.

6. Summary

In this section, you learned how to set up event listeners, common event types, and practical usage examples. Mastering event handling is essential for creating interactive web applications.

7. Common Practical Use Cases and Applied Scenarios

The JavaScript document object can be applied in many real-world scenarios. In this section, we introduce common use cases and applied scenarios frequently seen in actual development.

1. Dynamic form validation

Form input validation is important for improving user experience. Below is an example that checks input in real time.

HTML

<form id="signupForm">
  <label for="email">Email:</label>
  <input type="email" id="email" required>
  <span id="emailError" style="color: red;"></span>
  <br>
  <button type="submit">Submit</button>
</form>

JavaScript

let emailInput = document.getElementById("email");
let emailError = document.getElementById("emailError");
let form = document.getElementById("signupForm");

// Input validation
emailInput.addEventListener("input", () => {
    let emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailPattern.test(emailInput.value)) {
        emailError.textContent = "Please enter a valid email address.";
    } else {
        emailError.textContent = "";
    }
});

// Check on form submission
form.addEventListener("submit", (event) => {
    if (emailError.textContent !== "") {
        event.preventDefault();
        alert("There is an error in your input.");
    }
});

2. Dynamic content generation

This example dynamically generates new elements based on user actions.

HTML

<div id="container"></div>
<button id="addItem">Add item</button>

JavaScript

let container = document.getElementById("container");
let addButton = document.getElementById("addItem");

addButton.addEventListener("click", () => {
    let newItem = document.createElement("div");
    newItem.textContent = "New item";
    newItem.style.border = "1px solid #ccc";
    newItem.style.padding = "10px";
    newItem.style.margin = "5px 0";
    container.appendChild(newItem);
});

Result: A new item is added each time the button is clicked.

8. Cautions and Best Practices

The JavaScript document object is very powerful, but improper usage can negatively impact performance and security. In this section, we introduce important cautions and best practices to keep your code safe and efficient.

1. Performance optimization

1-1. 最小化 DOM 操作

DOM 操作成本高,因此应减少执行次数。

不良示例(在循环中重复的 DOM 操作)

for (let i = 0; i < 100; i++) {
    let div = document.createElement("div");
    div.textContent = "Item " + i;
    document.body.appendChild(div);
}

改进示例(使用 Document Fragment)

let fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
    let div = document.createElement("div");
    div.textContent = "Item " + i;
    fragment.appendChild(div);
}
document.body.appendChild(fragment);

关键点

  • 片段可以一次性追加到 DOM,提升性能。

1-2. 减少回流和重绘

频繁更改样式会导致回流和重绘,从而减慢渲染速度。

不良示例

let box = document.getElementById("box");
box.style.width = "100px";
box.style.height = "100px";
box.style.backgroundColor = "red";

改进示例(批量更新)

let box = document.getElementById("box");
Object.assign(box.style, {
    width: "100px",
    height: "100px",
    backgroundColor: "red"
});

2. 安全注意事项

2-1. 防止 XSS 攻击

使用 innerHTML 可能导致恶意脚本被注入。

危险示例

let userInput = "<script>alert('Attack!')</script>";
document.getElementById("output").innerHTML = userInput;

安全示例

let userInput = "<script>alert('Attack!')</script>";
document.getElementById("output").textContent = userInput;

关键点

  • 在显示之前始终对用户输入进行消毒(过滤)。

2-2. 正确管理事件监听器

如果未移除不再使用的事件监听器,可能导致内存泄漏。

不良示例

document.getElementById("button").addEventListener("click", () => {
    alert("Clicked!");
});

改进示例(在不再需要时移除监听器)

function handleClick() {
    alert("Clicked!");
}
let button = document.getElementById("button");
button.addEventListener("click", handleClick);
button.removeEventListener("click", handleClick);

3. 可读性与可维护性

3-1. 一致的命名约定

使用能清晰表明其作用的描述性变量和函数名。

不良示例

let a = document.getElementById("username");
let b = document.getElementById("password");

改进示例

let usernameInput = document.getElementById("username");
let passwordInput = document.getElementById("password");

3-2. 创建可复用函数

通过将代码重构为函数,可减少重复并提升可维护性。

不良示例

document.getElementById("btn1").addEventListener("click", () => alert("Button 1"));
document.getElementById("btn2").addEventListener("click", () => alert("Button 2"));

改进示例

function handleClick(message) {
    alert(message);
}

document.getElementById("btn1").addEventListener("click", () => handleClick("Button 1"));
document.getElementById("btn2").addEventListener("click", () => handleClick("Button 2"));

4. 移动端与响应式考虑

使用 JavaScript 时,也要确保在移动设备上的流畅表现。

技巧与对策

  1. 点击事件的替代方案 – 在移动端,可考虑使用 touchstarttouchend
  2. 视口设置 – 正确配置视口,以防止不必要的缩放。
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
  1. 结合媒体查询 – 使用 CSS 媒体查询实现响应式布局。

5. 总结

本节介绍了安全高效使用 document 对象的重要注意事项和最佳实践。

. 性能优化:最小化 DOM 操作。
安全性:防止 XSS 并安全处理用户输入。
可维护性:编写可读且可复用的代码。
移动支持:考虑响应式设计和触摸事件。

9. 常见问题解答:初学者常见问题

初学者在使用 JavaScript document 对象时常会遇到各种问题和疑问。本节以问答形式解答常见问题。

Q1. 为什么无法使用 getElementById() 选择元素?

A:
常见原因包括以下几点:

  1. ID 不正确
  • 指定的 ID 不存在或拼写错误。
  • 解决方案:检查 HTML 中的 ID 是否与 JavaScript 中使用的相匹配。
  1. 脚本执行时机
  • 如果 JavaScript 在 HTML 加载之前运行,元素尚未存在。
  • 解决方案:使用 DOMContentLoaded 事件。
    document.addEventListener("DOMContentLoaded", () => {
        let element = document.getElementById("myDiv");
        console.log(element.textContent);
    });
    

Q2. innerHTMLtextContent 有何区别?

A:

  • innerHTML:获取或设置包括 HTML 标签在内的所有内容。
  • textContent:仅获取或设置文本内容(HTML 标签会被忽略)。

Q3. 为什么无法修改 querySelectorAll() 返回的元素?

A:
querySelectorAll() 返回的是静态 NodeList,它不是数组。必须遍历它才能进行修改。

let items = document.querySelectorAll(".item");
items.forEach(item => {
    item.style.color = "blue";
});

Q4. 为什么 addEventListener() 无法工作?

A:
可能的原因包括:

  1. 元素未找到
  • 目标元素未被正确选取。
  • 解决方案:在控制台检查该元素是否存在。

Q5. 为什么 removeChild() 会抛出错误?

A:
被移除的元素必须是父元素的子节点。

let list = document.getElementById("list");
let item = document.getElementById("item1");
list.removeChild(item);

6. 小结

本 FAQ 部分针对初学者常见的问题提供了解答。关注元素选择、执行时机以及正确的方法使用,可帮助你避免许多问题。

10. 结论与后续步骤

在整篇文章中,你已经从基础概念到实际应用学习了 JavaScript document 对象。让我们回顾关键要点,并展望进一步学习的后续步骤。

掌握 document 对象后,你将拥有构建动态、交互式和高效 Web 应用的基础。接下来,你可以深入研究高级 DOM 操作、API 集成以及现代框架,以进一步提升技能。

広告