document.querySelector和querySelectorAll方法

来源:互联网 发布:淘宝试衣间在哪里 编辑:程序博客网 时间:2024/05/06 19:31
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 support13.5 (1.9.1)
bug 4163179
8 (CSS2 selectors only)103.2 (525.3)
WebKit bug 16587
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileBasic support2.1yes910.03.2
0 0
原创粉丝点击