querySelect()
這個比較簡單和直接,給幾個例子即可了解
獲取文檔中 class="example" 的第一個元素:
document.querySelector(".example");
獲取文檔中第一個 <p> 元素: document.querySelector("p");
假定你選擇了兩個選擇器: <h2> 和 <h3> 元素。 以下代碼將為文檔的第一個 <h2> 元素添加背景顏色,因為我們只能從上到下篩選出第一個 存在於篩選器中的標簽: <h2>A h2 element</h2> <h3>A h3 element</h3> document.querySelector("h2, h3").style.backgroundColor = "red";
獲取文檔中 class="example" 的第一個 <p> 元素: document.querySelector("p.example");
querySelectAll()
這個顧名思義,是篩選出所有符合條件的標簽。生成一個 NodeList (節點列表) , 我們可以懶惰的通過下標進行訪問。
// 獲取文檔中所有的 <p> 元素 var x = document.querySelectorAll("p"); // 設置第一個 <p> 元素的背景顏色 x[0].style.backgroundColor = "red";
// 獲取文檔中所有 class="example" 的 <p> 元素 var x = document.querySelectorAll("p.example"); // 設置 class="example" 的第一個 <p> 元素的背景顏色 x[0].style.backgroundColor = "red";
獲取文檔中有 "target" 屬性的第一個 <a> 元素: document.querySelector("a[target]");
計算文檔中 class="example" 的 <p> 元素的數量(使用 NodeList 對象的 length 屬性): var len = document.querySelectorAll(".example").length;
var x = document.querySelectorAll(".example"); var i; for (i = 0; i < x.length; i++) { x[i].style.backgroundColor = "red"; }
var x = document.querySelectorAll("div > p"); var i; for (i = 0; i < x.length; i++) { x[i].style.backgroundColor = "red"; }
經過了上面的閱讀,我們發現,實際上 selector 最重要的就是括號內那部分,即 我們怎樣編寫選擇器決定了我們篩選出來的內容是什么。
所以這里有一個 CSS選擇器網站,可供參考