querySelector() 方法


返回文檔中匹配指定 CSS 選擇器的一個元素。

雖然IE8中沒有getElementsByClassName()但可以用querySelector()代替

注意: querySelector() 方法僅僅返回匹配指定選擇器的第一個元素。如果你需要返回所有的元素,請使用 querySelectorAll() 方法替代。

querySelector

獲取文檔中 class="example" 的第一個元素:

document.querySelector(".example");

querySelectorAll

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

var x=document.querySelectorAll("p.example");
x[0].style.backgroundColor='red';

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

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM