DOM 树与节点类型
入门
DOM(Document Object Model)不是一段 HTML 字符串,而是浏览器解析文档后建立的一棵节点树。
树根是 document,向下依次是 html、head 与 body,
再往下是具体元素、文本与注释。每个节点都是对象,拥有属性与方法,脚本通过这层对象接口访问页面,
而不是去修改原始 HTML 文本。
节点用 nodeType 区分:1 表示元素,3 表示文本,8 表示注释,9 表示文档,11 表示文档片段。
children 只包含元素子节点,childNodes 则包含文本与注释;
parentNode、firstChild、nextSibling 这些指针把整棵树串起来。
HTML 里的换行与缩进同样会产生文本节点,这正是“遍历结果总比预期多几项”的常见原因。
查询得到的 Element 与 NodeList 都活在这棵树上,但可用 API 并不相同:
文本节点没有 querySelector,元素节点也不该用 nodeValue 去读文本。
动手前先确认手里拿到的是元素还是节点,能省掉大量判空与类型判断。
递归遍历并识别节点类型
// 用递归遍历真实 DOM 子树,观察节点的不同类型
function walk(node, depth) {
const pad = ' '.repeat(depth);
const type = node.nodeType;
let label = '';
if (type === Node.ELEMENT_NODE) {
label = '元素 <' + node.tagName.toLowerCase() + '>';
} else if (type === Node.TEXT_NODE) {
label = '文本 "' + node.nodeValue.trim().slice(0, 12) + '"';
} else if (type === Node.COMMENT_NODE) {
label = '注释';
} else {
label = '其他类型 ' + type;
}
// 纯空白的文本节点只会干扰阅读,直接跳过
if (type === Node.TEXT_NODE && !node.nodeValue.trim()) return;
console.log(pad + label);
// childNodes 含文本与注释,children 只含元素
for (let i = 0; i < node.childNodes.length; i++) {
walk(node.childNodes[i], depth + 1);
}
}
console.log('document 的 nodeType 是', document.nodeType); // 9
console.log('根元素是', document.documentElement.tagName); // HTML
walk(document.body, 0);
// 常见常量:1 元素、3 文本、8 注释、9 文档、11 文档片段
为什么遍历结果里有空白文本节点。HTML 中的换行、缩进在解析后都会成为 nodeType = 3 的文本节点。需要按结构遍历时用 children;需要完整还原内容时用 childNodes,并记得过滤空白。