DocumentFragment: querySelector() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

DocumentFragment.querySelector() 方法會在 DocumentFragment 中(使用深度優先的預序遍歷文件節點)查詢與指定選擇器組匹配的第一個元素,如果找不到匹配項,則返回 null

如果選擇器匹配一個 ID,並且該 ID 在文件中被錯誤地使用了多次,它將返回第一個匹配的元素。

如果引數中指定的選擇器無效,則會引發一個具有 SYNTAX_ERR 值的 DOMException

語法

js
querySelector(selectors)

引數

選擇器 (selectors)

包含一個或多個由逗號分隔的 CSS 選擇器的字串。

返回值

一個 Element 物件,代表文件中與指定的 CSS 選擇器 匹配的第一個元素;如果沒有匹配項,則返回 null

示例

基本示例

在這個基本示例中,將返回 DocumentFragment 中第一個具有 myclass 類的元素。

js
const el = documentfragment.querySelector(".myclass");

CSS 語法和方法的引數

傳遞給 querySelector 的字串引數必須遵循 CSS 語法。要匹配 ID 或不遵循 CSS 語法的選擇器(例如,不恰當地使用分號或空格),必須用雙反斜槓轉義錯誤字元。

html
<div id="foo\bar"></div>
<div id="foo:bar"></div>
js
document.querySelector("#foo\bar"); // Does not match anything
document.querySelector("#foo\\\\bar"); // Match the first div
document.querySelector("#foo:bar"); // Does not match anything
document.querySelector("#foo\\:bar"); // Match the second div

規範

規範
DOM
# ref-for-dom-parentnode-queryselector①

瀏覽器相容性

另見