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

瀏覽器相容性

另見