document.querySelector和querySelectorAll方法

querySelector和querySelectorAll是W3C提供的 新的查询接口,其主要特点如下:


1、querySelector只返回匹配的第一个元素,如果没有匹配项,返回null。 
2、querySelectorAll返回匹配的元素集合,如果没有匹配项,返回空的nodelist(节点数组)。 
3、返回的结果是静态的,之后对document结构的改变不会影响到之前取到的结果。 
 
这两个方法都可以接受三种类型的参数:id(#),class(.),标签,很像jquery的选择器。

var obj = document.querySelector("#id");

var obj = document.querySelector(".classname");
var obj = document.querySelector("div");
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("#id1, #id2, .class1, class2, div a, #list li img");
目前IE8+,ff,chrome都支持此api(IE8中的selector string只支持css2.1的)
浏览器支持查看
 
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support 1 3.5 (1.9.1)
bug 416317
9
8 (CSS2 selectors only)
10 3.2 (525.3)
WebKit bug 16587
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support 2.1 yes 9 10.0 3.2
posted @ 2017-04-11 15:44  原味咖啡厅  阅读(1250)  评论(0编辑  收藏  举报