Node: lookupPrefix() 方法

Baseline 已广泛支持

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

lookupPrefix() 方法是 Node 接口的一部分,用于返回给定命名空间 URI 的前缀(如果存在),如果不存在则返回 null。当存在多个可能的前缀时,将返回第一个前缀。

语法

js
lookupPrefix(namespace)

参数

namespace

一个字符串,表示要查找前缀的命名空间。

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

返回值

一个字符串,包含相应的命名空间前缀;如果没有找到,则返回 null。如果 namespace 为 null 或空字符串,则 lookupPrefix() 返回 null

如果节点是 DocumentTypeDocumentFragmentlookupPrefix() 始终返回 null

示例

html
Prefix for <code>http://www.w3.org/2000/svg</code> on &lt;output&gt;:
<output>Not tested</output>.<br />
Prefix for <code>http://www.w3.org/XML/1998/namespace</code> on &lt;output&gt;:
<output>Not tested</output>.<br />
Prefix for <code>http://www.w3.org/TR/html4/</code> on &lt;output&gt;:
<output>Not tested</output>.<br />
Prefix for <code>https://www.w3.org/1999/xlink</code> on &lt;output&gt;:
<output>Not tested</output>.<br />
Prefix for <code>http://www.w3.org/2000/svg</code> on &lt;svg&gt;:
<output>Not tested</output>.<br />
Prefix for <code>https://www.w3.org/1999/xlink</code> on &lt;svg&gt;:
<output>Not tested</output>.<br />
Prefix for <code>http://www.w3.org/XML/1998/namespace</code> on &lt;svg&gt;:
<output>Not tested</output>.<br />
<svg xmlns:t="http://www.w3.org/2000/svg" height="1"></svg>
<button>Click to see the results</button>
js
const button = document.querySelector("button");
button.addEventListener("click", () => {
  const htmlElt = document.querySelector("output");
  const svgElt = document.querySelector("svg");

  const result = document.getElementsByTagName("output");
  result[0].value = htmlElt.lookupPrefix("http://www.w3.org/2000/svg"); // true
  result[1].value = htmlElt.lookupPrefix(
    "http://www.w3.org/XML/1998/namespace",
  ); // false
  result[2].value = htmlElt.lookupPrefix("http://www.w3.org/TR/html4/"); // true
  result[3].value = htmlElt.lookupPrefix("https://www.w3.org/1999/xlink"); // false
  result[4].value = svgElt.lookupPrefix("http://www.w3.org/2000/svg"); // true
  result[5].value = svgElt.lookupPrefix("https://www.w3.org/1999/xlink"); // true
  result[6].value = svgElt.lookupPrefix("http://www.w3.org/XML/1998/namespace"); // false
});

规范

规范
DOM
# dom-node-lookupprefix

浏览器兼容性