js queryselector是什么呢?不知道的小伙伴來看看小編今天的分享吧!
1、js queryselector簡介:
js中querySelector()方法是返回文檔中匹配指定CSS選擇器的一個元素。
注意: querySelector() 方法僅僅返回匹配指定選擇器的第一個元素。如果需要返回所有的元素,使用 querySelectorAll() 方法替代。
如:
var body = document.querySelector('body');
var mydiv = document.querySelector('#mydiv');
var myclass = document.querySelector('.selected');
以上三個用來代替getElementById()和getElementByTagName().
其次如果要限定范圍查找 則可以
var img = document.body.querySelector('img.button');
相對于querySelectorAll(); 則是取得一個NodeList
2、語法
document.querySelector(CSS selectors)
拓展資料:
js選擇器:querySelector和querySelectorAll
二者區別:
querySelector是單一選擇器,得到的是唯一的一個元素;
querySelectorAll,得到的是一個數組,所有名為“*”的集合;
有點類似于jquery中id選擇器和class選擇一,id必須是唯一的,class是一組,querySelector用來選擇唯一的id,querySelectorAll用來選擇重復出現的元素或者class,當然理解是這樣的,如果頁面僅有一個唯一class,你用querySelector也可以!
用法:
let box = document.querySelector(".box");//單一元素生效 box.onclick = function(){ box.style.background= "red"; } let boxs = document.querySelectorAll(".box");//等到的是“.box”的集合 boxs[0].onclick = function(){ boxs[0].style.background= "red"; }
以上就是小編今天的分享了,希望可以幫助到大家。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com