怎样的深入理解querySelector(All)

  querySelector和querySelectorAll同属于Selectors API Level 1规范,该规范早在2006年就已经开始发展,并在2007年10月形成querySelector(All)的雏形。由于规范发展的够早,所以除了IE6、 7以外,所有浏览器都基本支持。这两个方法可以作用到Element、Document、DocumentFragment实例上面,即:

复制代码
var elem = document.getElementById("test"),
      frag = document.createDocumentFragment();

frag.appendChild(document.createElement("div"));

elem.querySelector("p");// Element, querySelectorAll

document.querySelector("div");// Document, querySelectorAll
document.body.querySelector("div");// querySelectorAll

frag.querySelector("div");// documentFragment, querySelectorAll
复制代码

      方法接收唯一的一个参数,该参数可为任意合法的CSS选择器字符串。不过在IE8下,对于大部分的CSS3选择器都不支持(只支持相邻兄弟element1~element2;属性选择器[attr^=val][attr$=val],[attr*=val])。除此之外,如果想要在IE8下使用伪元素选择器,需要用:,而不是CSS3规定的::(css3选择器的浏览器支持参考:http://caniuse.com/#search=nth-of-type)。

      Selectors API返回的内容是静态的NodeList,这和get系列、document.images返回动态的集合(NodeList、HTMLCollection)是不一样的。

 

      Selectors API虽然好用,不过在使用的时候还是需要注意一些问题。以下面代码为例:

<body>
<div id="test"><p>test</p></div>
</body>
var ele = document.getElementById("test");
ele.querySelector("div p").length; // A
jQuery(ele).find("div p").length; // B
ele.querySelector("body p").length; // C
jQuery(ele).find("body p").length; // D

       对于代码A,返回值为1,;代码B,返回值为0。代码C,返回值仍为1;代码D,返回值为0。(结果适用于所有支持Selectors API的浏览器)

      对于习惯使用jQuery的人来说,上面的结果可能有点接受不了。不过在规范中明确写明:

Even though the method is invoked on an element, selectors are still evaluated in the context of the entire document. In the following example, the method will still match the div element's child p element, even though the body element is not a descendant of the div element itself.

var div = document.getElementById("bar");
var p = div.querySelector("body p");
      一句话,Selectors API选择器的查找范围仍旧是document,只不过在查找完毕之后会判断元素是否位于ele的子树中。elem.querySelector(All)(str)相当于document.querySelector(All)(str)和elem子树的交集。
      个人猜想,W3C设计Selectors API的初衷就是为了达到和在CSS样式表中写相同的css Selector选中的元素完全相同的效果。而在样式表中,并没有作用范围的概念,所有css选择器的“作用域”都是整个文档(:scope除外,该伪元素可以指定css选择器的作用范围。目前IE、opera不支持)。
 
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 
      google了一下,翻到了jQuery作者在08年关于这个问题的一篇文章( http://ejohn.org/blog/thoughts-on-queryselectorall)。 John Resig和Prototype、Dojo的作者都认为Selector API没有作用范围是个明显的错误。文章里面还有john和规范制定者的一些关于这个问题的来往邮件,有兴趣的话可以看一下( http://lists.w3.org/Archives/Public/public-webapi/2008Apr/thread.html#msg251)。
 
      我想,这也是w3c制定 Selectors API Level 2的原因。在这个规范中,提出了find、findAll方法,实际上就和jQuery的find方法效果一致了,这两个方法目前还没有浏览器支持。除此之外,还有一个matches方法,用于判断元素是否和选择器匹配,该方法在各个浏览器的实现为( https://developer.mozilla.org/en-US/docs/Web/API/Element.matches):
      
 
      在jQuery1.4.2以及之前的版本的Sizzle实现中,只使用了document.querySelectorAll这个方法。在1.4.3以后开始使用elem.querySeectorAll。为了避免作用范围的问题,jQuery在使用该方法时先定了必须是元素才可使用该方法,然后首先把该元素的原有id存到一个变量里面,接着将元素ID设为"__sizzle__",最后在选择器中手动添加ID来限定选择范围。操作完之后再把ID设为原来的值(原来没有ID则直接remove掉)。代码如下:
复制代码
                                // qSA works strangely on Element-rooted queries
                // We can work around this by specifying an extra ID on the root
                // and working up from there (Thanks to Andrew Dupont for the technique)
                // IE 8 doesn't work on object elements
                } else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
                    var old = context.id, id = context.id = "__sizzle__";

                    try {
                        return makeArray( context.querySelectorAll( "#" + id + " " + query ), extra );

                    } catch(pseudoError) {
                    } finally {
                        if ( old ) {
                            context.id = old;

                        } else {
                            context.removeAttribute( "id" );
                        }
                    }
                }
复制代码

     不过,如果文档中真的有的元素id为“__sizzle__”,这个方法应该就会悲剧了。

 

     在zepto中,并没有针对elem使用querySelector(All)时的特殊处理,So:

复制代码
<!DOCTYPE html>
<html>
<head>
<script src="http://zeptojs.com/zepto.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div id="a"><div><p></p></div></div>
</body>
<script>
var ele = Zepto("#a").find("body div div p");
alert(ele.length); // 1
</script>
</html>
复制代码

 

希望zepto可以尽快修改这个问题,以求达到从jQuery到Zepto更好的迁移。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值