XPathResult: singleNodeValue 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

XPathResult 接口的只读 singleNodeValue 属性,当结果的 XPathResult.resultTypeANY_UNORDERED_NODE_TYPEFIRST_ORDERED_NODE_TYPE 且未匹配到任何节点时,返回一个 Node 值或 null

返回值是 Document.evaluate() 返回的 XPathResultNode 值。

异常

TYPE_ERR

如果 XPathResult.resultType 不是 ANY_UNORDERED_NODE_TYPEFIRST_ORDERED_NODE_TYPE,则会抛出一个 TYPE_ERR 类型的 DOMException

示例

下面的示例展示了 singleNodeValue 属性的用法。

HTML

html
<div>XPath example</div>
<div>
  Tag name of the element having the text content 'XPath example':
  <output></output>
</div>

JavaScript

js
const xpath = "//*[text()='XPath example']";
const result = document.evaluate(
  xpath,
  document,
  null,
  XPathResult.FIRST_ORDERED_NODE_TYPE,
  null,
);
document.querySelector("output").textContent = result.singleNodeValue.localName;

结果

规范

规范
DOM
# dom-xpathresult-singlenodevalue

浏览器兼容性