首页 > 技术文章 > javascript -- (浅谈querySelector和querySelectorAll)

zhao12354 2016-08-23 21:31 原文

W3规范:


 

  querySelector:

return the first matching Element node within the node's subtress. if there is no such node, the method must return null.

返回指定元素节点的子树中匹配selector的集合中的第一个,如果没有匹配,返回null.

  querySelectorAll:

return a NodeList containing all of the matching Element nodes within the node's subtrees, in document order. If there are no such nodes, the method must return an empty NodeList

返回指定元素节点的子树中匹配selector的节点集合,采用的是深度优化预查找;如果没有匹配的,这个方法返回空集合


 

简单理解:

querySelector()方法返回文档中匹配指定css选择器的一个元素,如果没有找到返回null。通过Document类型调用querySelector方法时,会在文档元素范围内查找匹配的元素,通过Element类型调用querySelector方法时只会在该元素后代元素范围内查找匹配的元素。如果传入了不被支持的选择符,querySelector()会抛出错误。

*:querySelector()方法仅返回匹配指定选择器的第一个元素。如果需要返回所有的元素,需要使用querySelectorAll()方法

语法:

document.querySelector(css, selector);

参数值:

css: String(类型)  描述:不可省略,指定一个或多个匹配元素的css选择器。可以使用他们的id、类、类型、属性、属性值等来选取元素。    对于多个选择器,使用逗号隔开,返回一个匹配的元素

eg: 获取文档中的第一个<p>元素:

document.querySelector('p');

获取文档中class = "box"的第一个元素:

document.querySelector('.box');

获取文档中有"target"属性的第一个<a>元素:

document.querySelector('a[target]');

/***多个选择器的使用方法**/

<span>hello</span>

<h2>world</h2>

document.querySelector('span,h2').style.color = 'blue';

querySelectorAll()方法:返回的所有而不仅仅是一个元素。这个方法返回的是一个NodeList类型实例而且是静态集合。querySelectorAll优点是返回的值实际上是带有所有属性和方法的NodeList实例,而其底层实现则类似于一组元素的快照,而非不断对文档进行搜索的动态查询,这样实现可以避免使用NodeList对象通常会引起大多数性能上的问题。如果没有找到匹配的元素,返回空的NodeList实例(类数组)。如果传入了不被支持的选择符,querySelectorAll()会抛错。

  

推荐阅读