Element.querySelector()

这篇翻译不完整。请帮忙从英语翻译这篇文章

返回第一个元素, 调用它的元素的一个后代,该元素与指定的选择器组匹配。

语法

element = baseElement.querySelector(selectors);
  • elementbaseElementelement 对象.
  • selectors 是一个CSS选择器字符串( selectors )

参数

selectors
A group of selectors to match the descendant elements of the Element baseElement against; this must be valid CSS syntax, or a SyntaxError exception will occur. The first element found which matches this group of selectors is returned.

返回值

The first descendant element of baseElement which matches the specified group of selectors. The entire hierarchy of elements is considered when matching, including those outside the set of elements including baseElement and its descendants; in other words, selectors is first applied to the whole document, not the baseElement, to generate an initial list of potential elements. The resulting elements are then examined to see if they are descendants of baseElement. The first match of those remaining elements is returned by the querySelector() method.

如果没有找到匹配项,返回值为null。

例外

SyntaxError
指定的选择器无效。

例子

我们来看几个例子。

查找一个特定元素的一个具有一个特定值的属性

In this first example, the first <style> element which either has no type or has type "text/css" in the HTML document body is returned:

let el = document.body.querySelector("style[type='text/css'], style:not([type])");

整个层次结构计数

下面的例子演示了在应用选择器时考虑整个文档的层次结构, 因此在定位匹配时仍然考虑指定的 baseElement 之外的级别。

HTML

<div>
  <h5>Original content</h5>
  <p>
    inside paragraph
    <span>inside span</span>
    inside paragraph
  </p>
</div>
<div>
  <h5>Output</h5>
  <div id="output"></div>
</div>

JavaScript

var baseElement = document.querySelector("p");
document.getElementById("output").innerHTML =
         (baseElement.querySelector("div span").innerHTML);

结果

The result looks like this:

Notice how the "div span" selector still matches the <span> element, even though the baseElement excludes the div element which is part of the specified selector.

更多例子

See Document.querySelector() for additional examples of the proper format for the selectors.

规范

规范 Status Comment
DOM4
querySelectorAll()
Recommendation  
Selectors API Level 2
querySelectorAll()
Working Draft  
Selectors API Level 1
querySelectorAll()
Recommendation  

浏览器兼容性

浏览器 支持 备注
Internet Explorer 8 CSS 2.1 selectors only (IE8)
Firefox (Gecko) 3.5 (1.9.1)  
Opera 10  
Chrome 1  
Safari (webkit) 3.2 (525.3) webk.it/16587

 

相关链接

文档标签和贡献者

 此页面的贡献者: xgqfrms-GitHub, KngZhi, ziyunfei, teoli, cuixiping, AlexChao
 最后编辑者: xgqfrms-GitHub,