querySelector
是 JavaScript 中用于选择 DOM 元素的最强大方法之一,它允许你使用 CSS 选择器语法来查找元素。
基本语法
// 返回文档中第一个匹配指定 CSS 选择器的元素
element = document.querySelector(selectors);// 从指定元素后代中查找
element = parentElement.querySelector(selectors);
参数说明
- selectors:一个 CSS 选择器字符串,用于匹配元素
- 可以是标签名、类名、ID、属性选择器、伪类等
- 支持复杂的 CSS 选择器组合
返回值
- 返回匹配的第一个元素(即使有多个匹配)
- 如果没有找到匹配项,返回
null
使用示例
1. 基本选择器
// 通过标签名选择
const div = document.querySelector('div');// 通过类名选择
const item = document.querySelector('.item');// 通过ID选择(虽然不如getElementById高效)
const header = document.querySelector('#header');
2. 组合选择器
// 后代选择器
const listItem = document.querySelector('ul li.first');// 子元素选择器
const directChild = document.querySelector('div > p.special');// 多个选择器(返回第一个匹配的)
const firstMatch = document.querySelector('.class1, .class2, #id1');
3. 属性选择器
// 具有特定属性的元素
const img = document.querySelector('img[alt]');// 属性值匹配
const link = document.querySelector('a[href="https://example.com"]');// 属性值包含
const input = document.querySelector('input[name*="user"]');
4. 伪类选择器
// 第一个子元素
const first = document.querySelector('li:first-child');// 悬停状态的元素(实际只能获取静态匹配)
const hovered = document.querySelector('p:hover'); // 注意:这不会动态更新// nth-child
const third = document.querySelector('tr:nth-child(3)');
5. 从特定元素开始查找
const container = document.querySelector('.container');
// 只在container内查找
const button = container.querySelector('button.primary');
与 querySelectorAll
的区别
特性 | querySelector | querySelectorAll |
---|---|---|
返回值 | 单个元素(第一个匹配) | NodeList(所有匹配元素) |
无匹配时返回 | null | 空 NodeList(长度为0) |
性能 | 略快(找到第一个就停止) | 需要查找所有匹配项 |
注意事项
-
性能考虑:
- 对于简单的 ID 查找,
getElementById
更快 - 对于简单的类名查找,
getElementsByClassName
可能更快 - 复杂选择器使用
querySelector
更方便
- 对于简单的 ID 查找,
-
动态性:
- 返回的是元素的静态引用,不是"活"的集合
- 如果 DOM 变化,需要重新查询
-
错误处理:
// 安全的使用方式 const element = document.querySelector('.possibly-missing'); if (element) {element.style.color = 'red'; }
-
复杂选择器:
- 支持所有 CSS3 选择器,包括
:not()
,:has()
等(注意浏览器兼容性)
- 支持所有 CSS3 选择器,包括
实际应用示例
// 查找表单中第一个无效的输入项
const firstInvalid = document.querySelector('form input:invalid');// 查找数据属性匹配的元素
const item = document.querySelector('[data-id="1234"]');// 查找特定状态的复选框
const checkedBox = document.querySelector('input[type="checkbox"]:checked');// 结合多种选择器
const highlight = document.querySelector('.post:not(.read) > .title');
浏览器兼容性
- 所有现代浏览器都支持(IE8+)
- 对于非常旧的浏览器,可能需要 polyfill 或使用其他方法
querySelector
是现代 JavaScript 开发中最常用的 DOM 查询方法之一,因为它提供了灵活且强大的选择能力,代码可读性高。