DOM(Document Object Model)將 HTML/XML 文檔表示為層次化節點樹,提供 API 讓 JS 動態操作頁面結構、樣式與內容。本文系統講解 DOM 核心概念與常用操作。
一、DOM 核心概念
- Document:整個網頁文檔,
document 對象是入口。
- Object:每個標籤、屬性、文本都是對象,擁有屬性方法。
- Model:樹形結構,
html 為根節點,形成父子兄弟關系。
三大節點類型
| 類型 | nodeType | 示例 |
| 元素節點 | 1 | <div> |
| 屬性節點 | 2 | id="box" |
| 文本節點 | 3 | 內容文本 |
二、元素查找:定位節點的 6 大方法
| 方法 | 返回值 | 說明 |
| getElementById(id) | Element / null | 唯一 ID 精確查找,最快 |
| getElementsByTagName(tag) | HTMLCollection (即時) | 標籤名查找,* 獲取所有 |
| getElementsByName(name) | NodeList (靜態) | name 屬性查找,表單常用 |
| querySelector(selector) | Element / null | CSS 選擇器,首個匹配 |
| querySelectorAll(selector) | NodeList (靜態) | CSS 選擇器,所有匹配 |
現代推薦:querySelector 系列
document.querySelector('#box'); // ID
document.querySelector('.box'); // Class
document.querySelector('div > p:first-child'); // 復雜選擇器
document.querySelectorAll('input[type="text"]'); // 所有文本框
三、元素屬性操作
1. 標準屬性(DOM Property)
const div = document.getElementById('box');
div.id; // 獲取/設置 id
div.className; // class(保留字用 className)
div.style.color = 'red'; // 行內樣式
div.href; // 鏈接地址
div.value; // 表單值
2. 通用屬性方法(Attribute)
div.getAttribute('data-id'); // 獲取任意屬性(含自定義)
div.setAttribute('data-id', 1); // 設置屬性
div.removeAttribute('style'); // 移除屬性
div.hasAttribute('hidden'); // 判斷存在性
區別:Property 是 JS 對象屬性,實時同步;Attribute 是 HTML 標記屬性,初始值來源。推薦用 Property,自定義屬性用 data-* + dataset。
3. dataset:HTML5 數據屬性專用
<div id="user" data-id="123" data-role="admin"></div>
const el = document.getElementById('user');
el.dataset.id; // "123"
el.dataset.role; // "admin"
el.dataset.nickName = 'Lee'; // 設置 data-nick-name
四、節點層級屬性:遍歷 DOM 樹
| 屬性 | 說明 |
| parentNode | 父節點(最近的 Element) |
| childNodes | 所有子節點(含文本/註釋) |
| children | 所有子元素節點(推薦,僅 Element) |
| firstChild / lastChild | 首尾子節點(含文本) |
| firstElementChild / lastElementChild | 首尾子元素(推薦) |
| previousSibling / nextSibling | 相鄰兄弟節點(含文本) |
| previousElementSibling / nextElementSibling | 相鄰兄弟元素(推薦) |
遍歷實戰:只處理元素節點
const box = document.getElementById('box');
for (const child of box.children) { // 僅元素
console.log(child.tagName);
}
// 或使用 childNodes 判斷 nodeType
for (const node of box.childNodes) {
if (node.nodeType === 1) console.log('元素:', node.tagName);
else if (node.nodeType === 3) console.log('文本:', node.nodeValue);
}
五、innerHTML vs nodeValue vs textContent
| 屬性 | 適用節點 | 行為 | 安全性 |
| innerHTML | Element | 解析 HTML,可執行腳本 | ⚠️ XSS 風險 |
| textContent | 所有 | 純文本,自動轉義 | ✅ 安全 |
| nodeValue | Text/Comment/Attr | 節點原始值 | 純文本 |
box.innerHTML = '<strong>bold</strong>'; // 渲染為粗體
box.textContent = '<strong>bold</strong>'; // 顯示原文
box.firstChild.nodeValue = '<strong>bold</strong>'; // 同 textContent
六、節點增刪改
// 創建
const el = document.createElement('div');
el.textContent = '新節點';
// 插入
parent.appendChild(el); // 末尾
parent.insertBefore(el, refNode); // 指定節點前
// 替換
parent.replaceChild(newEl, oldEl);
// 刪除
parent.removeChild(el);
// 現代:el.remove()(直接在自身調用)
總結
DOM 操作核心是「查找 → 修改」。熟練掌握 querySelector、classList、dataset、children/firstElementChild 等現代 API,配合 textContent 防 XSS,能編寫高效、安全、可維護的 DOM 代碼。