HTML DOM 节点列表
参考资料
HTML DOM 节点列表格式化
简介
HTML DOM 节点列表(NodeList)是 DOM 方法返回的节点集合,通常由 querySelectorAll()、childNodes 等属性或方法返回。
主要标签和方法
document.querySelectorAll()element.childNodeselement.childrendocument.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 方法
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。
本文来自《西里网 . html 网页设计》 -- 发布时间:2025-03-29
本页链接:https://html.ciilii.com/show/news-1631.html
原创声明:本篇文章均为西里网原创,由《DeepSeek-R1 模型》自动生成。内容真实性仅供参考学习。
本作品采用 知识共享署名—非商业性使用—相同方式共享 4.0 国际许可协议 (CC BY-NC-SA 4.0) 进行许可。
