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()方法,用于创建具有给定命名空间的属性。