Attr: namespaceURI 屬性
Attr 介面的只讀 namespaceURI 屬性返回屬性的名稱空間 URI,如果元素不在名稱空間中,則返回 null。
名稱空間 URI 在 Attr 建立時設定,並且無法更改。可以使用 Element.setAttributeNS() 建立一個帶名稱空間的屬性。
注意: 屬性不會繼承其附加到的元素的名稱空間。如果屬性沒有顯式地賦予名稱空間,則它沒有名稱空間。
瀏覽器本身不處理或強制執行名稱空間驗證。JavaScript 應用程式需要自行執行任何必要的驗證。另請注意,名稱空間字首一旦與特定屬性節點關聯,就無法更改。
值
一個包含名稱空間 URI 的字串,如果屬性不在名稱空間中,則返回 null。
示例
以下示例展示了 HTML 元素和 SVG 元素情況下帶字首屬性的結果。由於 HTML 不處理名稱空間,因此在這種情況下它將始終返回 null。對於 SVG 元素,它將返回 XML 名稱空間的 URI,即 http://www.w3.org/XML/1998/namespace。
HTML
html
<svg xml:lang="en-US" class="struct" height="1" width="1">Click me</svg>
<label xml:lang="en-US" class="struct"></label>
<p>
<button>Show value for <svg></button>
<button>Show value for <label></button>
</p>
<p>
Namespace URI of the attribute <code>xml:lang</code>:
<output id="result">None.</output>
</p>
JavaScript
js
const elements = document.querySelectorAll(".struct");
const buttons = document.querySelectorAll("button");
const outputEl = document.querySelector("#result");
let i = 0;
for (const button of buttons) {
const element = elements[i];
button.addEventListener("click", () => {
const attribute = element.attributes[0];
outputEl.value = attribute.namespaceURI;
});
i++;
}
規範
| 規範 |
|---|
| DOM # dom-attr-namespaceuri |
瀏覽器相容性
載入中…
另見
Attr.name屬性,返回屬性的限定名稱;Attr.localName屬性,名稱的本地部分;以及Attr.prefix屬性,名稱空間字首。Element.namespaceURI屬性,與此屬性等效,但用於Element。Element.setAttributeNS()方法,用於建立具有給定名稱空間的屬性。