DOM Manipulation
学习到 读取 and 修改 DOM — 创建, 更新, and 移除元素使用 JS.
你将学到
- 如何 选择元素使用 querySelector and querySelectorAll
- 创建 and appending 元素使用 createElement and appendChild
- 更新内容使用 textContent and innerHTML (and difference)
- 移除 and replacing 元素 in DOM 树
概念讲解
DOM 操作
The DOM (Document Object Model) is the browser's live, in-memory representation of your HTML page. JavaScript can read and modify this tree — change text, add elements, update attributes, alter styles — and the browser re-renders instantly. This is how every dynamic web feature works: a todo list adds items, a search filters results, a modal opens and closes.
Selecting Elements
Before you can manipulate an element, you must find it. The two primary methods are:
document.querySelector(selector)— returns the first matching element (or空). Uses CSS selector syntax:.card,#请求头,nav.document.querySelectorAll(selector)— returns a NodeList of all matches. Iterate with.forEach()or convert to an array with数组.从().
These replace the older getElementById, getElementsByClassName, and getElementsByTagName. The querySelector methods are more flexible because they accept any CSS selector.
Creating Elements
To add new content, create an element with document.createElement(tagName), configure it, then insert it into the DOM:
const li = document.createElement("li");
li.textContent = "新项";
li.className = "list-item";
document.querySelector("ul").appendChild(li);
appendChild adds the element as the last child. Use prepend, insertBefore, or insertAdjacentHTML for other positions.
textContent vs. innerHTML
textContent sets the text of an element — it is safe from XSS because the content is treated as plain text. innerHTML sets the HTML markup — it can insert elements, but it is dangerous with user input because it can execute injected scripts (XSS). Use textContent when you only need text. Use innerHTML only with trusted, sanitized content — never with raw user input.
Removing Elements
To remove an element, call 元素.移除(). To replace one element with another, use parent.replaceChild(newEl, oldEl). These operations update the DOM immediately, and the browser re-renders. For performance with large lists, consider batching changes or using a DocumentFragment to avoid multiple reflows.
示例代码
// Building a dynamic todo list with DOM manipulation
const input = document.querySelector("#todo-input");
const list = document.querySelector("#todo-list");
const button = document.querySelector("#add-btn");
button.addEventListener("click", () => {
const text = input.value.trim();
if (!text) return;
// Create the list item
const li = document.createElement("li");
li.className = "todo-item";
// Create a span for the text (safe from XSS)
const span = document.createElement("span");
span.textContent = text; // NOT innerHTML — prevents XSS
// Create a delete button
const del = document.createElement("button");
del.textContent = "Delete";
del.addEventListener("click", () => li.remove());
// Assemble and insert
li.append(span, del);
list.appendChild(li);
// Reset the input
input.value = "";
});
createElement 构建新 DOM 节点. textContent safely 设置文本不使用 XSS risk. append inserts 多个 children at 一次. 删除 button calls li.移除() 到移除项. 每个 interaction 更新 DOM and 浏览器 re-渲染 instantly.
动手试一试
- Markdown Previewer
这个 tool manipulates DOM in 真实时间 as 你类型 — watch preview 更新.
- HTML Entity Encoder
Encoding entities 是必要当 inserting 用户文本到 DOM safely.
常见错误
错误写法
Using innerHTML 使用用户输入, 创建 XSS vulnerability.
正确做法
Use textContent for 任何文本那个 comes 从用户. 它 treats 输入 as plain 文本, 不 HTML. 仅 use innerHTML 使用 trusted, sanitized 内容 — 从不使用 raw 用户字符串.
错误写法
Calling document.querySelector 之前元素 exists in DOM.
正确做法
位置你的 <script> at 端的 <请求体>, or wrap 你的 code in DOMContentLoaded 事件监听器. 否则 querySelector 返回空 and 你的 code throws 当你 try 到 use result.
相关资源
相关代码片段
- JavaScript 数组方法
数组方法 for transforming 数据之前渲染它 到 DOM.
相关速查表
- JavaScript Cheatsheet
引用 for DOM 方法: querySelector, createElement, append, 移除.
练习 DOM Manipulation
8 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。