`
haibin369
  • 浏览: 58743 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Javscript中的Selector API

阅读更多

在JQuery中使用CSS选择器获取元素非常方便,其实Javascript也提供了原生API去通过CSS选择器取得元素:querySelector(), querySelectorAll(). (完整支持的浏览器有:IE 8+, Firefox 3.5+, Safari 3.1+,
Chrome,  Opera 10+)

 

以下是W3C对Selector API两个方法的定义(http://www.w3.org/TR/selectors-api):

W3C Selectors API Level 1 写道
The querySelector() methods on the Document, DocumentFragment, and Element interfaces must return the first matching Element node within the subtrees of the context node. If there is no matching Element, the method must return null.

 

W3C Selectors API Level 1 写道
The querySelectorAll() methods on the Document, DocumentFragment, and Element interfaces must return a NodeList containing all of the matching Element nodes within the subtrees of the context node, in document order. If there are no matching nodes, the method must return an empty NodeList.

 

例子:有如下HTML片段

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Selectors API Example</title>
    </head>
    <body>
        <div id="foo">
            <p class="warning">This is a sample warning</p>
            <p class="error">This is a sample error</p>
        </div>
        <div id="bar">
            <p>...</p>
        </div>
    </body>
</html>

 使用Selector API获取元素:

/*
   querySelector()会返回第一个匹配的元素, querySelectorAll()会
   返回所有匹配元素的NodeList(静态,不随页面元素改变而更新)。两个
   方法都能在Document, DocumentFragment, 和Element上调用,表示在
   给定元素范围下查找元素。
 */

//得到第一个id为"foo"或者"bar"的元素(<div id="foo"/>)
var barOrFoo = document.querySelector("#foo, #bar");

//在<div id='foo'/>下查找第一个<p/>元素
var p = barOrFoo.querySelector("p");

//查找所有的<p/>元素
var pList = document.querySelectorAll("p");

//当使用这两个方法查找子元素的时候要特别注意,如下例子,我们想
//在<div id="foo"/>下查找子div中带warning类的<p/>元素,但是
//<div id="foo"/>下并无子<div/>,因此应该返回null,但是实际上
//方法返回了<p class="warning"/>
var warning = barOrFoo.querySelector("div p.warning");
alert(warning == null);  //false

 关于最后一个例子,和我们平时用JQuery的选择器获得的结果不一样,这个问题,W3C给出如下解释(http://www.w3.org/TR/selectors-api/#examples0):

W3C Selectors API Level 1 写道
Even though the method is invoked on an element, selectors are still evaluated in the context of the entire document.

 因此,即使在元素上调用Selector API,依然会在Document范围内查找匹配元素,只是在查找完后会判断每一个结果是否在调用元素的范围内(即是否是调用元素的后代元素),若不在则过滤掉。

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics