Element:querySelector() 方法
Element 介面的 querySelector() 方法返回第一個與指定選擇器組匹配的元素,該元素是呼叫此方法的元素的後代。
語法
querySelector(selectors)
引數
選擇器 (selectors)-
一個包含一個或多個要匹配的選擇器的字串。該字串必須是有效的 CSS 選擇器字串;如果不是,將丟擲
SyntaxError異常。請注意,HTML 規範不要求屬性值是有效的 CSS 識別符號。如果
class或id屬性值不是有效的 CSS 識別符號,那麼在使用它作為選擇器之前,您必須對其進行轉義,可以透過對該值呼叫CSS.escape(),或者使用 跳脫字元 中描述的一種技術。有關示例,請參見 轉義屬性值。
返回值
baseElement 的第一個匹配指定選擇器組的後代元素。匹配時會考慮整個元素層次結構,包括 baseElement 及其後代之外的元素;換句話說,selectors 首先應用於整個文件,而不是 baseElement,以生成潛在元素的初始列表。然後檢查結果元素,看它們是否是 baseElement 的後代。querySelector() 方法返回這些剩餘元素中的第一個匹配項。
如果沒有找到匹配項,返回值為 null。
異常
SyntaxErrorDOMException-
如果指定的
selectors無效,則丟擲異常。
示例
我們來看幾個例子。
查詢具有特定屬性值的特定元素
在第一個示例中,返回 HTML 文件正文中第一個既沒有型別,或型別為“text/css”的 <style> 元素
const el = document.body.querySelector(
"style[type='text/css'], style:not([type])",
);
使用 :scope 偽類獲取直接後代
此示例使用 :scope 偽類檢索 parentElement 元素的直接子元素。
HTML
<div>
<h6>Page Title</h6>
<div id="parent">
<span>Love is Kind.</span>
<span>
<span>Love is Patient.</span>
</span>
<span>
<span>Love is Selfless.</span>
</span>
</div>
</div>
CSS
span {
display: block;
margin-bottom: 5px;
}
.red span {
background-color: red;
padding: 5px;
}
JavaScript
const parentElement = document.querySelector("#parent");
let allChildren = parentElement.querySelectorAll(":scope > span");
allChildren.forEach((item) => item.classList.add("red"));
結果
整個層次結構都計算在內
此示例演示了在應用 selectors 時會考慮整個文件的層次結構,因此在查詢匹配項時仍然會考慮指定 baseElement 之外的級別。
HTML
<div>
<h5>Original content</h5>
<p>
inside paragraph
<span>inside span</span>
inside paragraph
</p>
</div>
<div>
<h5>Output</h5>
<div id="output"></div>
</div>
JavaScript
const baseElement = document.querySelector("p");
document.getElementById("output").textContent =
baseElement.querySelector("div span").textContent;
結果
結果如下所示
請注意,即使 baseElement 的子節點不包含 <div> 元素(它仍然是指定選擇器的一部分),"div span" 選擇器仍然成功匹配 <span> 元素。
轉義屬性值
此示例顯示,如果 HTML 文件包含的 id 不是有效的 CSS 識別符號,那麼在使用 querySelector() 之前,我們必須轉義屬性值。
HTML
在以下程式碼中,一個 <div> 元素的 id 是 "this?element",它不是一個有效的 CSS 識別符號,因為 CSS 識別符號中不允許使用 "?" 字元。
我們還有三個按鈕和一個用於記錄錯誤的 <pre> 元素。
<div id="container">
<div id="this?element"></div>
</div>
<button id="no-escape">No escape</button>
<button id="css-escape">CSS.escape()</button>
<button id="manual-escape">Manual escape</button>
<pre id="log"></pre>
CSS
div {
background-color: blue;
margin: 1rem 0;
height: 100px;
width: 200px;
}
JavaScript
所有三個按鈕在點選時都會嘗試選擇 <div>,然後將其背景顏色設定為隨機值。
- 第一個按鈕直接使用
"this?element"值。 - 第二個按鈕使用
CSS.escape()來轉義該值。 - 第三個按鈕使用反斜槓明確轉義
"?"字元。請注意,我們還必須使用另一個反斜槓來轉義反斜槓本身,例如:"\\?"。
const container = document.querySelector("#container");
const log = document.querySelector("#log");
function random(number) {
return Math.floor(Math.random() * number);
}
function setBackgroundColor(id) {
log.textContent = "";
try {
const element = container.querySelector(`#${id}`);
const randomColor = `rgb(${random(255)} ${random(255)} ${random(255)})`;
element.style.backgroundColor = randomColor;
} catch (e) {
log.textContent = e;
}
}
document.querySelector("#no-escape").addEventListener("click", () => {
setBackgroundColor("this?element");
});
document.querySelector("#css-escape").addEventListener("click", () => {
setBackgroundColor(CSS.escape("this?element"));
});
document.querySelector("#manual-escape").addEventListener("click", () => {
setBackgroundColor("this\\?element");
});
結果
點選第一個按鈕會報錯,而第二個和第三個按鈕則正常工作。
更多示例
有關 selectors 正確格式的其他示例,請參閱 Document.querySelector()。
規範
| 規範 |
|---|
| DOM # ref-for-dom-parentnode-queryselectorall① |
瀏覽器相容性
載入中…
另見
- DOM 樹上的選擇與遍歷
- CSS 指南中的屬性選擇器
- MDN 學習區中的屬性選擇器
Element.querySelectorAll()Document.querySelector()和Document.querySelectorAll()DocumentFragment.querySelector()和DocumentFragment.querySelectorAll()- 其他接受選擇器的方法:
element.closest()和element.matches()。