1.querySelector():返回匹配的第一个元素,若没有匹配项,返回null
2.querySelectorAll():返回匹配的元素集合,若没有匹配项,返回空的nodelist节点数组
3.返回的结果是静态的,dom结构改变不会更新之前取到的结果
浏览器支持:
目前 IE8+,ff,chrome 都支持此API
(IE8中的selector string 只支持css2.1的)
Feature
Chrome
Firefox (Gecko)
Internet Explorer
Opera
Safari (WebKit)
Basic support
1
3.5 (1.9.1)
bug 416317
9
8 (CSS2 selectors only)
10
Feature
Android
Firefox Mobile (Gecko)
IE Mobile
Opera Mobile
Safari Mobile
Basic support
2.1
yes
9
10.0
3.2
接受参数:合法的css选择器语法
ele = document.querySelector(“selectors”);
eleList = document.querySelectorAll(“selectors”);
其中,selectors可以包含多个css选择器,用逗号隔开
ele = document.queryselector(“selector1,selector2,…”);
eleList = document.queryselectorAll(“selector1,selector2,…”);
关于转义的问题:具体参见 http://www.cnblogs.com/Wayou/p/html5_web_api_queryselector.html
其中两个例子的个人理解:
1.document.querySelector("fo:bar")=>document.querySelector("fo\\:bar")
因为'\'本身就是转义符号,所以在字符串中要先将'\'转义,这是第一个'\'的作用
然后被转义位'\'的字符与':'字符结合,完成对':'字符对转义之后形成的字符串才能被querySelector理解为'fo:bar'.
2.document.querySelector("fo\bar")=>document.querySelector("fo\\\\bar")
前两个'\'字符与上一个例子中的作用相同,第三个'\'的作用是把该id字符串中的'\'转义为'\'字符,然后两个被转义后的'\'结合才能被querySelector()理解为'fo\bar'.
单个selector:
var obj = document.querySelector(“#id”);
var obj = document.querySelector(“.class”);
var obj = document.querySelector(“tagName”);
多个selectors:
var el = document.body.querySelector("style[type='text/css'], style:not([type])”);
var elements = document.querySelectorAll(“#score>tbody>tr>td:nth-of-type(2)”);
var elements = document.querySelectorAll(“#div1,#div2,.class1,.class2,div a,#list li img”);