JS querySelectorAll 获取元素列表并遍历
概述
querySelectorAll 是现代 JavaScript 中最常用的 DOM 查询方法,支持 CSS 选择器语法,返回匹配的元素列表。掌握它的遍历技巧能大幅提升开发效率。
基本用法
// 获取所有匹配元素
var items = document.querySelectorAll(".my-class");
var links = document.querySelectorAll("a[target='_blank']");
var cells = document.querySelectorAll("th div i a span span");四种遍历方式
1. forEach(最推荐)
document.querySelectorAll(".item").forEach((item, index) => {
console.log(index, item.textContent);
});2. 传统 for 循环(兼容性最好)
var items = document.querySelectorAll(".item");
for (var i = 0; i < items.length; i++) {
console.log(items[i].textContent);
}3. for...of(ES6+)
for (const item of document.querySelectorAll(".item")) {
console.log(item.textContent);
}4. 转数组后使用 map/filter
// querySelectorAll 返回的是 NodeList,需要先转数组
var texts = Array.from(document.querySelectorAll(".item"))
.filter(item => item.textContent.includes("关键字"))
.map(item => item.textContent);常用选择器示例
// 按类名
document.querySelectorAll(".active")
// 按属性
document.querySelectorAll("[data-type='primary']")
// 组合选择器
document.querySelectorAll("div.container > ul > li")
// 多选择器
document.querySelectorAll("h2, h3, h4")常见场景
- 批量修改表格单元格样式
- 提取页面中所有链接地址
- 给一组按钮统一绑定事件
- 扫描页面内容做自动化处理
注意事项
querySelectorAll返回的是 NodeList(静态列表),DOM 变化不会自动更新- 不是真正的数组,需要
Array.from()转换后才能用map、filter - 匹配不到元素时返回空 NodeList(不是 null),forEach 不会报错
暂无评论
快来发表第一条评论吧!