HTML5:原生DOM选择器,类jquery

1.querySelector():返回匹配的第一个元素,若没有匹配项,返回null

2.querySelectorAll():返回匹配的元素集合,若没有匹配项,返回空的nodelist节点数组

3.返回的结果是静态的,dom结构改变不会更新之前取到的结果

 

浏览器支持:

目前 IE8+,ff,chrome 都支持此API

(IE8中的selector string 只支持css2.1的)

 

FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support13.5 (1.9.1)
bug 416317
9
8 (CSS2 selectors only)
103.2 (525.3)
WebKit bug 16587
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support2.1yes910.03.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”);

转载于:https://my.oschina.net/u/2618661/blog/743566

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值