document.querySelectorAll返回静态NodeList,包含所有匹配CSS选择器的DOM元素;支持各类合法选择器,但需转数组才能用map等方法,区别于querySelector只返首个元素。

document.querySelectorAll 是 JS 中获取符合 CSS 选择器的所有元素的最常用方法,它返回一个 静态 NodeList(不是数组,但可遍历),包含所有匹配的 DOM 元素。
基本用法:传入合法 CSS 选择器字符串
只要浏览器支持的 CSS 选择器,基本都能用:
-
document.querySelectorAll('div')—— 所有<div>元素 -
document.querySelectorAll('.btn')—— 所有 class 为btn的元素 -
document.querySelectorAll('[data-id]')—— 所有带data-id属性的元素 -
document.querySelectorAll('input[type="text"]')—— 所有 type 为 text 的 input -
document.querySelectorAll('ul li:first-child')—— 每个 ul 下的第一个 li
注意:返回值不是数组,但可以转成数组操作
NodeList 不支持 map、filter 等数组方法(旧版 IE 中甚至不支持 forEach),常用转换方式:
- ES6+ 推荐:
Array.from(document.querySelectorAll('.item')) - 或展开运算符:
[...document.querySelectorAll('.item')] - 兼容老浏览器可用:
Array.prototype.slice.call(nodeList)
转换后就能放心调用 .map()、.forEach()、.find() 等方法了。
立即学习“前端免费学习笔记(深入)”;
和 querySelector 的区别要分清
querySelector 只返回第一个匹配元素(或 null),而 querySelectorAll 返回全部匹配元素组成的 NodeList(空时是空 NodeList,不是 null)。
-
document.querySelector('.card')→ 返回首个 .card 元素(Element 或 null) -
document.querySelectorAll('.card')→ 返回所有 .card 元素(NodeList,长度可能为 0)
常见易错点提醒
以下写法容易出问题,需注意:
- 选择器字符串必须是合法 CSS 语法,不能写 JS 变量名(如
document.querySelectorAll(myClass)要先拼成字符串:document.querySelectorAll('.' + myClass)) - 伪元素(如
::before)无法被选中 —— 它们不在 DOM 树中,querySelectorAll只匹配真实存在的元素节点 - 动态插入的元素,需在插入后再次调用,它不会自动更新(因为返回的是静态列表)
- 如果选择器语法错误(如漏引号、括号不匹配),会直接抛
SyntaxError,建议包裹 try/catch 做容错(尤其拼接选择器时)


















