Element:getAttributeNS() 方法

Baseline 已广泛支持

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

Element 接口的 getAttributeNS() 方法返回具有指定命名空间和名称的属性的字符串值。如果命名的属性不存在,则返回值将是 null""(空字符串);有关详细信息,请参阅 注意事项

如果您正在处理 HTML 文档,并且不需要将请求的属性指定为属于特定命名空间,请改用 getAttribute() 方法。

语法

js
getAttributeNS(namespace, name)

参数

namespace

要查找指定属性的命名空间。

name

要查找的属性的名称。

返回值

指定属性的字符串值。如果属性不存在,结果是 null

注意: DOM 规范的早期版本将此方法描述为对不存在的属性返回空字符串,但通常不会这样实现,因为 null 更符合逻辑。DOM4 规范现在规定此方法应对不存在的属性返回 null。

示例

下面的 SVG 文档读取自定义命名空间中 foo 属性的值。

xml
<svg xmlns="http://www.w3.org/2000/svg"
    xmlns:test="http://www.example.com/2014/test" width="40" height="40">

  <circle id="target" cx="12" cy="12" r="10" stroke="#444444"
      stroke-width="2" fill="none" test:foo="Hello namespaced attribute!"/>

  <script>
    const ns = 'http://www.example.com/2014/test';
    const circle = document.getElementById('target');

    console.log(`attribute test:foo: "${circle.getAttributeNS(ns, 'foo')}"`);
  </script>
</svg>

在 HTML 文档中,由于不支持命名空间,必须使用 test:foo 来访问该属性。

html
<svg
  xmlns="http://www.w3.org/2000/svg"
  xmlns:test="http://www.example.com/2014/test"
  width="40"
  height="40">
  <circle
    id="target"
    cx="12"
    cy="12"
    r="10"
    stroke="#444444"
    stroke-width="2"
    fill="none"
    test:foo="Foo value" />
</svg>
js
const ns = "http://www.example.com/2014/test";
const circle = document.getElementById("target");
console.log(`Attribute value: ${circle.getAttribute("test:foo")}`);

注意

getAttributeNS()getAttribute() 的区别在于,它允许您进一步将请求的属性指定为属于特定命名空间,如上例所示,其中该属性属于虚构的“test”命名空间。

在 DOM4 规范之前,此方法被指定为对不存在的属性返回空字符串而不是 null。然而,大多数浏览器返回的是 null。从 DOM4 开始,规范现在规定返回 null。不过,一些旧浏览器会返回空字符串。因此,如果请求的属性可能不存在于指定元素上,您应该在调用 getAttributeNS() 之前使用 hasAttributeNS() 来检查属性是否存在。

规范

规范
DOM
# ref-for-dom-element-getattributens①

浏览器兼容性

另见