解讀document.querySelector()方法
HTML 的DOM querySelector()方法可以不需要額外的jQuery等支持,也可以方便的獲取DOM元素,語法跟jQuery類似。
獲取文檔中id="container"的元素
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="contatiner">huang</div> <script type="text/javascript"> var destination = document.querySelector("#contatiner"); console.log(destination); </script> </body> </html>
注意:
querySelector() 方法僅僅返回匹配指定選擇器的第一個元素。如果你需要返回所有的元素,請使用 querySelectorAll() 方法替代。
參數(shù)類型可以為如下:
- 指定一個或多個匹配元素的 CSS 選擇器。 可以使用它們的 id, 類, 類型, 屬性, 屬性值等來選取元素。
- 對于多個選擇器,使用逗號隔開,返回一個匹配的元素。
獲取第一個p元素
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <p>張露露,我愛你</p> <p>黃寶康,我也愛你</p> <script type="text/javascript"> var node = document.querySelector("p"); console.log(node); </script> </body> </html>
獲取文檔中的第一個class="lover"的元素
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <span class="lover">張露露</span> <span class="lover">黃寶康</span> <script type="text/javascript"> var node = document.querySelector(".lover"); console.log(node); </script> </body> </html>
獲取class=“lover” 的第一個p元素
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <span class="lover">張露露</span> <p class="lover">黃寶康</p> <script type="text/javascript"> var node = document.querySelector("p.lover"); console.log(node); </script> </body> </html>
獲取第一個帶target屬性的a元素
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <a >百度一下</a> <a target="_blank">淘寶一下</a> <script type="text/javascript"> var node = document.querySelector("a[target]"); console.log(node); </script> </body> </html>
多個選擇器的使用方法
以下代碼將為文檔的第一個 <h2>
元素添加背景顏色:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h2>二級標(biāo)題</h2> <h3>三級標(biāo)題</h3> <script type="text/javascript"> document.querySelector("h2,h3").style.backgroundColor = "blue"; </script> </body> </html>
但是,如果文檔中 <h3>
元素位于 <h2>
元素之前,<h3>
元素將會被設(shè)置指定的背景顏色。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h3>三級標(biāo)題</h3> <h2>二級標(biāo)題</h2> <script type="text/javascript"> document.querySelector("h2,h3").style.backgroundColor = "blue"; </script> </body> </html>
總結(jié)
多元素選擇時,哪個先匹配就是誰咯,只有一個被選中。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
THREE.JS入門教程(4)創(chuàng)建粒子系統(tǒng)
Three.js是一個偉大的開源WebGL庫,WebGL允許JavaScript操作GPU,在瀏覽器端實現(xiàn)真正意義的3D本文將介紹創(chuàng)建一個粒子系統(tǒng)/風(fēng)格/引入物理等等,感興趣的朋友可以了解下哦,希望本文對你有所幫助2013-01-01caller和callee的區(qū)別介紹及演示結(jié)果
caller返回一個函數(shù)的引用,這個函數(shù)調(diào)用了當(dāng)前的函數(shù);callee放回正在執(zhí)行的函數(shù)本身的引用,它是arguments的一個屬性,感興趣的你可以參考下或許可以幫助到你2013-03-03javascript中attribute和property的區(qū)別詳解
這篇文章主要介紹了javascript中attribute和property的區(qū)別詳解,attribute和property對新手來說,特別容易混淆概念,本文就清晰的講解了它們的區(qū)別,需要的朋友可以參考下2014-06-06