当前位置: 移动技术网 > IT编程>开发语言>JavaScript > jQuery选择器querySelector的使用指南

jQuery选择器querySelector的使用指南

2019年03月31日  | 移动技术网IT编程  | 我要评论

简介

html5向web api新引入了document.queryselector以及document.queryselectorall两个方法用来更方便地从dom选取元素,功能类似于jquery的选择器。这使得在编写原生javascript代码时方便了许多。
用法

两个方法使用差不多的语法,都是接收一个字符串参数,这个参数需要是合法的css选择语法。

代码如下:


element = document.queryselector('selectors');
elementlist = document.queryselectorall('selectors');

其中参数selectors 可以包含多个css选择器,用逗号隔开。

代码如下:


element = document.queryselector('selector1,selector2,...');
elementlist = document.queryselectorall('selector1,selector2,...');

使用这两个方法无法查找带伪类状态的元素,比如queryselector(':hover')不会得到预期结果。

queryselector

代码如下:


element = document.queryselector('p#container');//返回id为container的首个p
element = document.queryselector('.foo,.bar');//返回带有foo或者bar样式类的首个元素

queryselectorall

该方法返回所有满足条件的元素,结果是个nodelist集合。查找规则与前面所述一样。

elements = document.queryselectorall('p.foo');//返回所有带foo类样式的p
需要注意的是返回的nodelist集合中的元素是非实时的.

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网