HTML DOM 节点列表
2025-04-24
30
参考资料
HTML DOM 节点列表
HTML DOM 节点列表格式化
简介
HTML DOM 节点列表(NodeList)是 DOM 方法返回的节点集合,通常由 querySelectorAll()
、childNodes
等属性或方法返回。
主要标签和方法
document.querySelectorAll()
element.childNodes
element.children
document.getElementsByTagName()
document.getElementsByClassName()
基本用法
获取节点列表
// 通过选择器获取 const nodeList = document.querySelectorAll('p'); // 通过子节点获取 const childNodes = document.body.childNodes; // 通过标签名获取 const elementsByTag = document.getElementsByTagName('div');
遍历节点列表
// 使用 for 循环 for (let i = 0; i < nodeList.length; i++) { console.log(nodeList[i]); } // 使用 forEach (仅适用于 querySelectorAll 返回的 NodeList) nodeList.forEach(node => { console.log(node); }); // 使用 ES6 扩展运算符转为数组 [...nodeList].forEach(node => { console.log(node); });
功能特性
类数组对象,有 length 属性
可以通过索引访问元素
动态或静态集合(取决于获取方式)
不是真正的数组,没有数组方法(除非转换)
CSS 扩展
可以通过 CSS 选择器来精确选择需要格式化的节点:
// 选择所有 class 为 highlight 的元素 const highlights = document.querySelectorAll('.highlight'); // 选择特定结构下的元素 const nestedItems = document.querySelectorAll('ul li > a');
示例说明
示例1:修改所有段落文本
const paragraphs = document.querySelectorAll('p'); paragraphs.forEach(p => { p.style.color = 'blue'; p.style.fontSize = '16px'; });
示例2:统计子元素数量
const container = document.getElementById('container'); const childCount = container.childNodes.length; console.log(`容器中有 ${childCount} 个子节点`);
示例3:动态过滤节点
const allDivs = document.querySelectorAll('div'); const visibleDivs = [...allDivs].filter(div => { return div.offsetWidth > 0 && div.offsetHeight > 0; }); console.log(`共有 ${visibleDivs.length} 个可见的 div 元素`);
示例4:批量添加事件
const buttons = document.querySelectorAll('.btn'); buttons.forEach(button => { button.addEventListener('click', function() { console.log('按钮被点击'); }); });
注意事项
querySelectorAll
返回的是静态集合getElementsByClassName
等返回的是动态集合节点列表不是数组,要使用数组方法需要先转换
某些旧版浏览器可能不支持 NodeList 的 forEach 方法