DOM遍历与选择器
DOM遍历与选择器API是操作页面元素的核心能力。
选择器API
querySelector
JavaScript
// 选择单个元素
const el = document.querySelector('.box');
const el = document.querySelector('#header');
const el = document.querySelector('div.container > p:first-child');
// 在特定元素内查询
const parent = document.querySelector('.container');
const child = parent.querySelector('.item');
querySelectorAll
JavaScript
// 选择所有匹配元素(返回 NodeList)
const items = document.querySelectorAll('.item');
const paragraphs = document.querySelectorAll('p');
// 遍历 NodeList
items.forEach(item => {
item.style.color = 'red';
});
// 转换为数组
const arr = Array.from(items);
const arr = [...items];
getElementById等传统方法
JavaScript
const el = document.getElementById('header');
const els = document.getElementsByClassName('item'); // HTMLCollection
const els = document.getElementsByTagName('div'); // HTMLCollection
const els = document.getElementsByName('username');
| 方法 | 返回类型 | 动态更新 |
|---|---|---|
querySelector | Element | 否 |
querySelectorAll | NodeList | 否 |
getElementsByClassName | HTMLCollection | 是 |
getElementsByTagName | HTMLCollection | 是 |
DOM遍历属性
父子关系
JavaScript
const el = document.querySelector('.item');
// 父元素
el.parentElement; // 直接父元素
el.parentNode; // 父节点(可能是非元素)
// 子元素
el.children; // 子元素集合
el.childNodes; // 所有子节点(含文本)
el.firstElementChild; // 第一个子元素
el.lastElementChild; // 最后一个子元素
el.firstChild; // 第一个子节点
el.lastChild; // 最后一个子节点
兄弟关系
JavaScript
// 元素兄弟
el.previousElementSibling; // 上一个兄弟元素
el.nextElementSibling; // 下一个兄弟元素
// 节点兄弟
el.previousSibling; // 上一个兄弟节点
el.nextSibling; // 下一个兄弟节点
Element vs Node对比
| Element方法 | Node方法 | 说明 |
|---|---|---|
children | childNodes | Element只含元素 |
firstElementChild | firstChild | Element跳过文本 |
previousElementSibling | previousSibling | Element只找元素 |
遍历方法
closest向上查找
JavaScript
// 查找最近的匹配祖先元素
const el = document.querySelector('.item');
const container = el.closest('.container');
const section = el.closest('section');
matches匹配检测
JavaScript
// 检查元素是否匹配选择器
const el = document.querySelector('.item');
if (el.matches('.item.active')) {
console.log('匹配');
}
NodeList与HTMLCollection
NodeList
JavaScript
const nodes = document.querySelectorAll('.item');
// forEach遍历
nodes.forEach(n => console.log(n));
// 获取长度
nodes.length;
// 索引访问
nodes[0];
// 转数组
Array.from(nodes);
HTMLCollection
JavaScript
const collection = document.getElementsByClassName('item');
// 无forEach方法
// 需转数组遍历
Array.from(collection).forEach(n => console.log(n));
// 或使用for循环
for (let i = 0; i < collection.length; i++) {
console.log(collection[i]);
}
动态vs静态
JavaScript
// querySelectorAll:静态(不更新)
const items1 = document.querySelectorAll('.item');
document.body.appendChild(document.createElement('div.item'));
console.log(items1.length); // 不变
// getElementsByClassName:动态(更新)
const items2 = document.getElementsByClassName('item');
document.body.appendChild(document.createElement('div.item'));
console.log(items2.length); // 增加一个
遍历所有后代元素
递归遍历
JavaScript
function walkDOM(root, callback) {
callback(root);
root = root.firstElementChild;
while (root) {
walkDOM(root, callback);
root = root.nextElementSibling;
}
}
walkDOM(document.body, (el) => {
console.log(el.tagName);
});
TreeWalker API
JavaScript
const walker = document.createTreeWalker(
document.body,
NodeFilter.SHOW_ELEMENT,
null
);
let node;
while (node = walker.nextNode()) {
console.log(node.tagName);
}
实际应用示例
查找并遍历
JavaScript
// 查找列表所有项
const items = document.querySelectorAll('ul > li');
items.forEach((item, index) => {
item.textContent = `项目 ${index + 1}`;
});
层级导航
JavaScript
const btn = document.querySelector('button');
// 找到父容器
const form = btn.closest('form');
// 遍历表单所有输入
const inputs = form.querySelectorAll('input');
inputs.forEach(input => {
console.log(input.name);
});
要点总结
- querySelector推荐:灵活选择,返回静态集合
- Element遍历:使用Element方法跳过文本节点
- closest向上:快速查找祖先匹配元素
- 动态vs静态:HTMLCollection动态更新,NodeList静态
📝 发现内容有误?点击此处直接编辑