Skip to content

DOM

选择元素, handling 事件, and 更新 page 使用 Document 对象 Model.

你将学到

  • 什么 DOM 是 and 如何浏览器构建它 从 HTML
  • 选择元素使用 querySelector and getElementById
  • 修改内容使用 textContent and innerHTML
  • Handling 事件使用 addEventListener
  • 创建 and appending 新元素

概念讲解

What Is the DOM?

The Document Object Model (DOM) is a live, tree-like representation of your HTML that JavaScript can read and modify. When the browser loads a page, it parses the HTML and builds this tree. Every HTML element becomes a node you can access via document.

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

Selecting Elements

// By ID — returns a single element or null
const title = document.getElementById("main-title");

// By CSS selector — first match only
const button = document.querySelector(".btn-primary");

// All matches — returns a NodeList
const items = document.querySelectorAll("li");

querySelector and querySelectorAll accept any CSS selector, so they are the most flexible and are the modern default.

Modifying Content

const heading = document.querySelector("h1");
heading.textContent = "更新 Title"; // safe — sets plain text
heading.innerHTML = "<span>HTML</span>"; // parses HTML — XSS risk!

Prefer textContent when you only need plain text. innerHTML parses the string as HTML, which can introduce cross-site scripting (XSS) vulnerabilities if the content includes user input.

Handling Events

const button = document.querySelector("button");
button.addEventListener("点击", (event) => {
  console.log("点击!", event.target);
});

Common events: 点击, 输入, 更改, 提交, keydown, mouseover. The callback receives an event object with details about what happened.

Creating and Appending Elements

const list = document.querySelector("ul");
const newItem = document.createElement("li");
newItem.textContent = " 新项";
newItem.classList.add("highlight");
list.appendChild(newItem);

classList for Styling

const card = document.querySelector(".card");
card.classList.add("active");
card.classList.remove("隐藏");
card.classList.toggle("选择"); // add if missing, remove if present

A Note on Frameworks

Modern apps often use React, Vue, or Svelte instead of touching the DOM directly. But understanding the DOM is essential — frameworks are abstractions over it, and you will still need it for browser extensions, vanilla scripts, and understanding how frameworks work under the hood.

示例代码

              // Select the button and the output area
const button = document.querySelector("#counter-btn");
const display = document.querySelector("#count-display");

let count = 0;

// Update the display
function updateDisplay() {
  display.textContent = `Count: ${count}`;
  // Toggle a CSS class based on the count
  display.classList.toggle("even", count % 2 === 0);
}

// Handle clicks
button.addEventListener("click", () => {
  count++;
  updateDisplay();

  // Dynamically create a log entry
  if (count <= 5) {
    const log = document.createElement("p");
    log.textContent = `Clicked ${count} time(s)`;
    document.querySelector("#log").appendChild(log);
  }
});

// Handle keyboard shortcuts
document.addEventListener("keydown", (e) => {
  if (e.key === "r") {
    count = 0;
    updateDisplay();
  }
});

updateDisplay(); // initialize
            

工作计数器: 选择元素, 更新 textContent safely, 切换 CSS 类, 创建 and appends log 条目, and listens for keyboard shortcuts. 粘贴这个到 page 使用 matching 元素.

动手试一试

常见错误

错误写法

Using innerHTML 使用用户输入 and 创建 XSS vulnerability

正确做法

从不 put untrusted 数据到 innerHTML. Use textContent for plain 文本, or sanitize HTML 首先. 框架如 React escape 值通过默认 for 这个 reason.

错误写法

Calling querySelector 之前元素 exists in DOM

正确做法

Put 你的 script at 端的 请求体, or wrap 它 in DOMContentLoaded: document.addEventListener('DOMContentLoaded', () => { ... }). 否则 querySelector 返回空.

相关代码片段

相关速查表

练习 DOM

9 个练习

练习 DOM

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误