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 查詢方法之一,因為它提供了靈活且強大的選擇能力,代碼可讀性高。