首页  >  文章  >  web前端  >  总结jQuery中querySelector选择器的用法详解

总结jQuery中querySelector选择器的用法详解

巴扎黑
巴扎黑原创
2017-06-21 09:49:442633浏览

这篇文章主要介绍了jQuery选择器querySelector的使用指南的相关资料,需要的朋友可以参考下

简介

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集合中的元素是非实时的.

以上是总结jQuery中querySelector选择器的用法详解的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn