Node: lookupNamespaceURI() 方法

Baseline 已广泛支持

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

Node 接口的 lookupNamespaceURI() 方法以一个前缀作为参数,并在找到时返回与给定节点上该前缀关联的命名空间 URI(如果未找到则返回 null)。该方法的存在允许将 Node 对象作为命名空间解析器传递给 XPathEvaluator.createExpression()XPathEvaluator.evaluate()

语法

js
lookupNamespaceURI(prefix)

参数

prefix

要查找的前缀。

注意: 此参数不是可选的,但可以设置为 null

返回值

与前缀对应的命名空间 URI 字符串。

  • 如果节点是 DocumentFragmentDocumentType、没有 documentElementDocument,或者没有关联元素的 Attr,则始终返回 null
  • 如果 prefix"xml",则返回值始终为 "http://www.w3.org/XML/1998/namespace"
  • 如果 prefix"xmlns",则返回值始终为 "http://www.w3.org/2000/xmlns/"
  • 如果 prefixnull,则返回值为默认命名空间 URI。
  • 如果未找到该前缀,则返回值为 null

示例

html
<div class="hidden">
  <div>Test HTML element</div>
  <svg>
    <text>Test SVG element</text>
  </svg>
  <math>Test MathML element</math>
</div>

<table>
  <thead>
    <tr>
      <th><code>prefix</code></th>
      <th><code>&lt;div&gt;</code></th>
      <th><code>&lt;svg&gt;</code></th>
      <th><code>&lt;math&gt;</code></th>
    </tr>
  </thead>
  <tbody></tbody>
</table>
js
const htmlElt = document.querySelector("div");
const svgElt = document.querySelector("svg");
const mathElt = document.querySelector("math");

const tbody = document.querySelector("tbody");

for (const prefix of ["xmlns", "xml", "html", "svg", "xlink", "", null]) {
  const row = document.createElement("tr");
  tbody.appendChild(row);
  row.appendChild(document.createElement("td")).textContent =
    JSON.stringify(prefix);
  for (const el of [htmlElt, svgElt, mathElt]) {
    console.log(el, prefix, el.lookupNamespaceURI(prefix));
    row.appendChild(document.createElement("td")).textContent = String(
      el.lookupNamespaceURI(prefix),
    );
  }
}

规范

规范
DOM
# dom-node-lookupnamespaceuri

浏览器兼容性

另见