HTML DOM Document querySelectorAll() 方法
- 上一頁
- 下一頁
- 返回上一層 HTML DOM Documents
定義和用法
querySelectorAll()
方法返回與 CSS 選擇器匹配的所有元素。
querySelectorAll()
方法返回的是 NodeList。
如果選擇器無效,則 querySelectorAll()
方法會拋出 SYNTAX_ERR
異常。
實例
例子 1
選擇所有帶有 class="example" 的元素:
document.querySelectorAll(".example");
例子 2
為第一個 <p> 元素添加背景顏色:
const nodeList= document.querySelectorAll("p"); nodeList[0].style.backgroundColor = "red";
例子 3
為第一個 class="example" 的 <p> 元素添加背景顏色:
const nodeList = document.querySelectorAll("p.example"); nodeList[0].style.backgroundColor = "red";
例子 4
class="example" 的元素的數量:
let numb = document.querySelectorAll(".example").length;
例子 5
設置所有 class="example" 的元素的背景顏色:
const nodeList = document.querySelectorAll(".example"); for (let i = 0; i < nodeList.length; i++) { nodeList[i].style.backgroundColor = "red"; }
例子 6
設置所有 <p> 元素的背景顏色:
let nodeList = document.querySelectorAll("p"); for (let i = 0; i < nodeList.length; i++) { nodeList[i].style.backgroundColor = "red"; }
例子 7
設置所有使用 "target" 屬性的 <a> 元素的邊框:
const nodeList = document.querySelectorAll("a[target]"); for (let i = 0; i < nodeList.length; i++) { nodeList[i].style.border = "10px solid red"; }
例子 8
設置父元素是 <div> 元素的每個 <p> 元素的背景顏色:
const nodeList = document.querySelectorAll("div > p"); for (let i = 0; i < nodeList.length; i++) { nodeList[i].style.backgroundColor = "red"; }
例子 9
設置所有 <h3>、<div> 和 <span> 元素的背景顏色:
const nodeList = document.querySelectorAll("h3, div, span"); for (let i = 0; i < nodeList.length; i++) { nodeList[i].style.backgroundColor = "red"; }
語法
document.querySelectorAll(CSSselectors)
參數
參數 | 描述 |
---|---|
CSSselectors |
必需。一個或多個 CSS 選擇器。 CSS 選擇器根據 id、類、類型、屬性、屬性值等選擇 HTML 元素。 如需完整列表,請訪問我們的 CSS 選擇器參考手冊。 對于多個選擇器,請用逗號分隔每個選擇器(請參閱上方的實例)。 |
返回值
類型 | 描述 |
---|---|
對象 |
含有與 CSS 選擇器匹配的元素的 NodeList 對象。 如果沒有找到匹配項,則返回空的 NodeList 對象。 |
HTMLCollection 和 NodeList 的區別
NodeList 和 HTMLcollection 非常相似。
兩者都是從文檔中提取的節點(元素)的類似數組的集合(列表)。可以通過索引號(下標)訪問節點。索引從 0 開始。
兩者都有 length 屬性,它返回列表(集合)中元素的數量。
HTMLCollection 是文檔元素的集合。
NodeList 是文檔節點(元素節點、屬性節點和文本節點)的集合。
HTMLCollection 項目可以通過它們的名稱、id 或索引號來訪問。
NodeList 項目只能通過它們的索引號訪問。
HTMLCollection 始終是實時的集合。
例如:如果將 <li> 元素添加到 DOM 中的列表,則 HTMLCollection 中的列表也會發生變化。
NodeList 通常是靜態的集合。
例如:如果將 <li> 元素添加到 DOM 中的列表,則 NodeList 中的列表不會改變。
getElementsByClassName()
和 getElementsByTagName()
方法都返回實時 HTMLCollection。
querySelectorAll()
方法返回靜態 NodeList。
childNodes
屬性返回實時 NodeList。
瀏覽器支持
document.querySelectorAll()
是 DOM Level 3 (2004) 特性。
所有瀏覽器都支持它:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
支持 | 9-11 | 支持 | 支持 | 支持 | 支持 |
相關頁面
教程:
QuerySelector 方法:
Document querySelectorAll() 方法
GetElement 方法:
- 上一頁
- 下一頁
- 返回上一層 HTML DOM Documents