HTML DOM querySelectorAll() 方法

Document 對象參考手冊 Document 對象

實例

獲取文檔中 class="example" 的所有元素:

var x = document.querySelectorAll(".example");


定義與用法

querySelectorAll() 方法返回文檔中匹配指定 CSS 選擇器的所有元素,返回 NodeList 對象。

NodeList 對象表示節點的集合。可以通過索引訪問,索引值從 0 開始。

提示: 你可以使用 NodeList 對象的 length 屬性來獲取匹配選擇器的元素屬性,然後你可以遍曆所有元素,從而獲取你想要的資訊。

更多 CSS 選擇器可以參考 CSS 選擇器教程CSS 選擇器參考手冊


流覽器支持

表格中的數字表示支持該方法的第一個流覽器的版本號。

方法
querySelectorAll() 4.0 9.0 3.5 3.2 10.0

注意: Internet Explorer 8 支持 CSS2 選擇器。 IE9 及更高版本的流覽器已經支持 CSS3 選擇器。


語法

elementList = document.querySelectorAll(selectors);
  • elementList 是一個靜態的 NodeList 類型的對象。
  • selectors 是一個由逗號連接的包含一個或多個 CSS 選擇器的字串。

屬性值

參數 類型 描述
CSS 選擇器 String 必須。 指定一個或多個匹配 CSS 選擇器的元素。可以通過 id, class, 類型, 屬性, 屬性值等作為選擇器來獲取元素。

多個選擇器使用逗號(,)分隔。

提示: CSS 選擇器更多內容可以參考 CSS 選擇器參考手冊

方法

DOM 版本: Level 1 Document Object
返回值: 一個 NodeList 對象,表示文檔中匹配指定 CSS 選擇器的所有元素。 NodeList 是一個靜態的 NodeList 類型的對象。如果指定的選擇器不合法,則拋出一個 SYNTAX_ERR 異常。

更多實例

實例

獲取文檔中所有的 <p> 元素, 並為匹配的第一個 <p> 元素 (索引為 0) 設置背景顏色:

// 獲取文檔中所有的 <p> 元素 var x = document.querySelectorAll("p"); // 設置第一個 <p> 元素的背景顏色 x[0].style.backgroundColor = "red";

實例

獲取文檔中所有 class="example" 的 <p> 元素, 並為匹配的第一個 <p> 元素 (索引為 0) 設置背景顏色:

// 獲取文檔中所有 class="example" 的 <p> 元素 var x = document.querySelectorAll("p.example"); // 設置 class="example" 的第一個 <p> 元素的背景顏色 x[0].style.backgroundColor = "red";

實例

計算文檔中 class="example" 的 <p> 元素的數量(使用 NodeList 對象的 length 屬性):

var x = document.querySelectorAll(".example").length;

實例

設置文檔中所有 class="example" 元素的背景顏色:

var x = document.querySelectorAll(".example"); var i; for (i = 0; i < x.length; i++) { x[i].style.backgroundColor = "red"; }

實例

設置文檔中所有 <p> 元素的背景顏色:

var x = document.querySelectorAll("p"); var i; for (i = 0; i < x.length; i++) { x[i].style.backgroundColor = "red"; }

實例

查找文檔中共包含 "target" 屬性的 <a> 標籤,並為其設置邊框:

var x = document.querySelectorAll("a[target]"); var i; for (i = 0; i < x.length; i++) { x[i].style.border = "10px solid red"; }

實例

查找每個父元素為 <div> 的 <p> 元素,並為其設置背景顏色:

var x = document.querySelectorAll("div > p"); var i; for (i = 0; i < x.length; i++) { x[i].style.backgroundColor = "red"; }

實例

給文檔中所有的 <h2>, <div> 和 <span> 元素設置背景顏色:

var x = document.querySelectorAll("h2, div, span"); var i; for (i = 0; i < x.length; i++) { x[i].style.backgroundColor = "red"; }


相關文章

CSS 教學: CSS 選擇器

CSS 參考手冊: CSS 選擇器參考手冊

JavaScript 教學: JavaScript HTML DOM 節點列表

HTML DOM 參考手冊: document.querySelector()

HTML DOM 參考手冊: element.querySelectorAll()


Document 對象參考手冊 Document 對象