querySelector
摘要
返回与提供的选择器匹配的第一个元素。
方法 of dom/Elementdom/Element
语法
var element = element.querySelector(/* see parameter list */);
参数
selectors
- 数据类型
- 字符串
一个选择器,或多个选择器(用逗号分隔)。
返回值
返回一个 DOM NodeDOM Node 类型的对象
一个 DOM 元素节点,如果搜索无法找到匹配选择器字符串的元素,则为 null。
示例
此示例说明选择器字符串中的选择器作用域限定为整个文档。变量 e 包含 span,即使提供的选择器引用了 P 元素,而 P 元素位于起始 DIV 元素的作用域之外。
<!doctype html>
<html>
<!-- To limit the search to descendants of an element only, -->
<!-- call the selectors API on the specific element of interest. -->
<body>
<p>
<div id="apple">
Some are sauce, some are pie.
</div>
</p>
<script>
var div = document.getElementById("apple");
var e = div.querySelector("p span"); // 'e' will select the span.
var f = div.querySelector("p div"); // 'f' will be null because the div is not a descendent of 'div'
</script>
</body>
</html>
备注
文档搜索顺序是深度优先。此方法返回找到的第一个元素。要查找所有匹配的节点,请使用 querySelectorAll。返回的元素节点的作用域限定为起始元素节点的后代。如果起始元素是 Document,则搜索返回整个文档中的节点。此方法不会返回起始元素节点。例如,div.querySelector("p div") 永远不会返回它开始的 DIV 元素。支持伪类选择器 :hover、:focus 和 :active。包含 :visited 或 :link 的选择器将被忽略,并且不会返回任何元素。您可以使用基于前缀而不是 namespaceURI 的选择器语法来搜索命名空间元素,例如 "nsPrefix \: element",其中“nsPrefix”是给定元素的前缀。选择器在理解 CSS 选择器和 W3C 选择器 中有详细描述。使用未知的选择器调用此方法(由于浏览器未实现它,或由于拼写错误等)可能会引发异常。
相关规范
- 选择器 API 级别 1
- 建议推荐
参见
相关页面
- Document
- a
addressbbigblockQuotebodybuttoncaptioncentercitecodecolcolGroupdddfndirdivdldtemfieldSetformhnhtmliimginput type=buttoninput type=checkboxinput type=fileinput type=imageinput type=passwordinput type=radioinput type=resetinput type=submitinput type=textisIndexkbdlabellegendlilistingmarqueemenunoBRolpplainTextpressampsmallspanstrikestrongsubsup- table
tBodytdtextAreatFootthtHeadtrttuulvarxmp参考- querySelectorAll
其他资源- [W3C 选择器 API]
- [W3C 选择器]
署名
Microsoft Developer Network: [Windows Internet Explorer API 参考 文章]