HTML DOM Document querySelectorAll()
描述
querySelectorAll()
方法返回所有匹配 CSS 選擇器的元素。
querySelectorAll()
方法返回一個 NodeList。
如果選擇器無效,querySelectorAll()
方法會丟擲 SYNTAX_ERR 異常
NodeList(節點列表)
NodeList 是一個類似陣列的節點集合(列表)。
列表中的節點可以透過索引訪問。索引從 0 開始。
length 屬性 返回列表中節點的數量。
語法
document.querySelectorAll(CSS 選擇器)
引數
引數 | 描述 |
CSS 選擇器 | 必需。 一個或多個 CSS 選擇器。 CSS 選擇器根據 ID、類、型別、屬性、屬性值等選擇 HTML 元素。 有關完整列表,請參閱我們的 CSS 選擇器參考。 對於多個選擇器,請用逗號分隔每個選擇器(參見“更多示例”)。 |
返回值
型別 | 描述 |
物件 | 一個 NodeList 物件,其中包含與 CSS 選擇器匹配的元素。 如果沒有找到匹配項,則返回一個空的 NodeList 物件。 |
更多示例
為第一個 <p> 元素新增背景顏色
const nodeList= document.querySelectorAll("p");
nodeList[0].style.backgroundColor = "red";
自己動手試一試 »
為第一個 class="example" 的 <p> 元素新增背景顏色
const nodeList = document.querySelectorAll("p.example");
nodeList[0].style.backgroundColor = "red";
自己動手試一試 »
設定所有 class="example" 的元素的背景顏色
const nodeList = document.querySelectorAll(".example");
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].style.backgroundColor = "red";
}
自己動手試一試 »
設定所有 <p> 元素的背景顏色
let nodeList = document.querySelectorAll("p");
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].style.backgroundColor = "red";
}
自己動手試一試 »
設定所有帶有 "target" 屬性的 <a> 元素的邊框
const nodeList = document.querySelectorAll("a[target]");
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].style.border = "10px solid red";
}
自己動手試一試 »
設定父元素是 <div> 元素的每個 <p> 元素的背景顏色
const nodeList = document.querySelectorAll("div > p");
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].style.backgroundColor = "red";
}
自己動手試一試 »
設定所有 <h3> 和 <span> 元素的背景顏色
const nodeList = document.querySelectorAll("h3, span");
for (let i = 0; i < nodeList.length; i++) {
nodeList[i].style.backgroundColor = "red";
}
自己動手試一試 »
瀏覽器支援
document.querySelectorAll()
是 DOM Level 3 (2004) 特性。
所有現代瀏覽器都完全支援它
Chrome | Edge | Firefox | Safari | Opera | IE |
是 | 是 | 是 | 是 | 是 | 11 |