Javscript中的Selector API

本文介绍了如何使用原生JavaScript中的querySelector()和querySelectorAll()方法来选取DOM元素,并给出了实际的例子,展示了这些方法如何在不同上下文中工作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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范围内查找匹配元素,只是在查找完后会判断每一个结果是否在调用元素的范围内(即是否是调用元素的后代元素),若不在则过滤掉。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值