$(selector, context) 接受 CSS 選擇器字串,回傳 **jQuery 包裝集** (類陣列物件),包含 0~n 個 DOM 元素。context 可選,限定搜尋範圍 (DOM/包裝集)。
$("#id") // ID 選擇器,最快
$(".class") // 類別
$("div") // 標籤
$("*") // 所有元素
$("div, span, p") // 群組 (並集)
$("#box .item") // 後代
$("#box > .item") // 子代
$("#box + .next") // 緊鄰下一個同輩
$("#box ~ .siblings") // 所有後面同輩
| 方向 | 方法 | 說明 |
|---|---|---|
| DOM → jQuery | $(domElement) | 單個元素包裝 |
| DOM 陣列 → jQuery | $(domArray) | 批量包裝 |
| jQuery → DOM (單個) | $("selector")[0] 或 .get(0) | 取得原生元素 |
| jQuery → DOM 陣列 | .get() 或 .toArray() | 原生陣列 |
| 迴圈中轉換 | .each(function(){ $(this)... }) | this 是 DOM |
技巧:IDE 智能提示能區分 DOM (原生屬性/方法) 與 jQuery (豐富 API)。
*, element, #id, .class, selector1, selector2 (群組)ancestor descendant (空格) — 後代parent > child — 直接子代prev + next — 緊鄰下一個同輩prev ~ siblings — 所有後面同輩| 語法 | 匹配條件 | 範例 |
|---|---|---|
[attr] | 擁有該屬性 | $("[data-id]") |
[attr=value] | 屬性等於值 | $("[type=text]") |
[attr!=value] | 屬性不等於值 | $("[type!=hidden]") |
[attr^=value] | 屬性以值開頭 | $("[id^=user-]") |
[attr$=value] | 屬性以值結尾 | $("[name$=_id]") |
[attr*=value] | 屬性包含值任意位置 | $("[class*=col-]") |
[attr|=value] | 屬性等於值或值-開頭 (語言代碼) | $("[lang|=en]") |
[attr~=value] | 屬性以空格分隔的值中包含 | $("[class~=highlight]") |
| 多屬性疊加 | 同時滿足 | $("[type=text][required]") |
:first, :last, :eq(n), :gt(n), :lt(n) — 索引 (0-based):even, :odd — 奇偶索引:header — h1~h6:animated — 正在動畫中:focus — 當前聚焦 (1.6+):root — 文檔根元素 (html):target — URL hash 對應元素:contains(text) — 包含指定文字 (大小寫敏感):empty — 無子節點 (含文字節點):has(selector) — 包含符合選擇器的後代:parent — 有子節點 (非空):visible — 佔據空間、非 display:none、非 type=hidden、非 width/height=0:hidden — 相反 (含 type=hidden、display:none、opacity:0 但佔空間者視為可見)| 選擇器 | 等價原生 | 匹配元素 |
|---|---|---|
:input | input, textarea, select, button | 所有表單控件 |
:text | [type=text] | 文字輸入框 |
:password | [type=password] | 密碼框 |
:radio | [type=radio] | 單選鈕 |
:checkbox | [type=checkbox] | 核取方塊 |
:submit | [type=submit] | 提交按鈕 |
:button | button + [type=button] | 按鈕 |
:file | [type=file] | 檔案上傳 |
:enabled | 無 disabled | 可用控件 |
:disabled | 有 disabled | 禁用控件 |
:checked | radio/checkbox/option 選中 | 勾選項 |
:selected | option 選中 | 下拉選中項 |
:first-child, :last-child, :only-child:nth-child(n), :nth-child(even/odd), :nth-child(3n+1) — **1-based** 索引,支援公式:nth-last-child(n) — 從後往前:first-of-type, :last-of-type, :only-of-type, :nth-of-type(n) — 同類型標籤中索引$("#id") 直接呼叫 getElementById。(".item", "#container") 限定範圍。$(".class") 比 $("div.class") 快 (現代瀏覽器 querySelectorAll 已優化,但習慣佳)。$("#box .item") 先找 .item 再找祖先 #box。document.querySelectorAll(".class") 回傳靜態 NodeList,效能更高,無 jQuery 開銷。$.expr[":"].external = function(el) {
return el.hostname && el.hostname !== location.hostname;
};
// 使用
$("a:external").addClass("external-link");
熟練掌握 jQuery 選擇器體系,是高效操作 DOM 的前提。實務上建議:**優先用 ID/類別/屬性選擇器,善用表單/可見性過濾器,複雜邏輯改用 .filter(fn) 而非堆疊偽類**。