| 方法 | 選擇器類型 | 返回類型 | 即時性 | 性能 |
|---|---|---|---|---|
getElementById(id) | ID | Element / null | 即時 | ⭐⭐⭐⭐⭐ 最快 |
getElementsByTagName(tag) | 標籤名 | HTMLCollection | 即時 | ⭐⭐⭐⭐ |
getElementsByClassName(class) | 類名 | HTMLCollection | 即時 | ⭐⭐⭐⭐ |
getElementsByName(name) | name 屬性 | NodeList | 即時 | ⭐⭐⭐ 主要用於表單 |
querySelector(selector) | CSS 選擇器 | Element / null | 靜態快照 | ⭐⭐⭐ |
querySelectorAll(selector) | CSS 選擇器 | NodeList | 靜態快照 | ⭐⭐⭐ |
<span id="unique">目標元素</span>
const el = document.getElementById('unique');
console.log(el.textContent); // "目標元素"
// ⚠️ 注意:ID 必須全局唯一,重複 ID 行為未定義
// ⚠️ 大小寫敏感:getElementById('Unique') 返回 null
<div>A</div><div>B</div><div>C</div>
const divs = document.getElementsByTagName('div');
// HTMLCollection(3) [div, div, div] - 即時集合
// 訪問方式
divs[0]; // 第一個
divs.item(1); // 第二個(同 [1])
divs.length; // 3
// 即時性演示
document.body.appendChild(document.createElement('div'));
console.log(divs.length); // 4 - 自動更新!
<div class="box active"></div>
<div class="box"></div>
<span class="box"></span>
const boxes = document.getElementsByClassName('box');
// HTMLCollection(3) [div, div, span]
// 多類名:空格分隔 = 交集
const activeBoxes = document.getElementsByClassName('box active');
// HTMLCollection(1) [div]
// 單個匹配(首個)
document.querySelector('.container .item:first-child');
document.querySelector('input[type="checkbox"]:checked');
// 所有匹配(靜態 NodeList)
const items = document.querySelectorAll('.list > li:nth-child(odd)');
// NodeList 支援 forEach(現代瀏覽器)
items.forEach(el => el.classList.add('highlight'));
// ⚠️ 靜態快照:DOM 變更不自動更新
const live = document.getElementsByClassName('item');
const static = document.querySelectorAll('.item');
// 新增 .item 元素 → live.length 增加,static.length 不變
// 存在屬性
document.querySelectorAll('[data-id]');
// 屬性值精確匹配
document.querySelectorAll('[data-role="admin"]');
// 屬性值前綴/後綴/包含
document.querySelectorAll('[href^="https://"]'); // 以 https:// 開頭
document.querySelectorAll('[src$=".png"]'); // 以 .png 結尾
document.querySelectorAll('[class*="btn-"]'); // 包含 btn-
// 多屬性 AND
document.querySelectorAll('[type="text"][required]');
:first-child, :last-child, :nth-child(2n), :nth-of-type(3)
:first-of-type, :last-of-type
:not(.hidden) // 否定
:empty // 無子節點(含文本)
:checked, :disabled, :enabled // 表單狀態
:focus, :hover // 交互狀態(querySelector 不觸發)
// 後代選擇器(空格)
document.querySelectorAll('ul li'); // ul 所有後代 li
// 子代選擇器 (>)
document.querySelectorAll('ul > li'); // ul 直接子元素 li
// 相鄰兄弟 (+)
document.querySelectorAll('h2 + p'); // 緊鄰 h2 後的 p
// 通用兄弟 (~)
document.querySelectorAll('h2 ~ p'); // h2 後所有同級 p
function getByClass(parent, className) {
const all = parent.getElementsByTagName('*');
const regex = new RegExp('(^|\\s)' + className + '(\\s|$)');
const result = [];
for (let i = 0; i < all.length; i++) {
if (regex.test(all[i].className)) {
result.push(all[i]);
}
}
return result;
}
// 使用
const items = getByClass(document, 'item');
為什麼用正則而非 className === 'item'? 因為元素可能有多個類名 class="item active highlight",精確匹配會失效。
| 場景 | 推薦方法 | 理由 |
|---|---|---|
| 已知唯一 ID | getElementById | 原生最快、語義明確 |
| 標籤名批量 | getElementsByTagName | 即時集合、極快 |
| 類名批量 | getElementsByClassName | 原生優化、即時 |
| 複雜 CSS 選擇器 | querySelectorAll | 功能最全、靜態快照安全 |
| 單一複雜匹配 | querySelector | 短路優化、返回首個 |
| 表單元素按 name | getElementsByName | 語義專用、處理同名單選框 |
「ID 優先、標籤次之、類名再次、選擇器最後;
即時集合記得轉數組,靜態快照放心遍歷;
作用域縮小查找快,避免全局 document 遍歷。」
掌握原生 DOM 查找 API 的返回類型差異(即時 vs 靜態)、選擇器表達力、性能特徵,是寫出高效、健壯原生 JS 代碼的基礎。現代開發中,優先使用 querySelectorAll 統一選擇器語法,僅在極致性能敏感路徑(如動畫幀、大列表渲染)才針對性優化到 getElementById/getElementsByClassName。