大网数据广告活动
Web 标准与前端开发

Element: getAttributeNS() method

· 52CE 我爱测

The **`getAttributeNS()`** method of the Element interface returns the string value of the specified namespaced attribute of the specified element. It returns `null` if the element doesn't have an attribute with the given name in the namespace.

DOM

The getAttributeNS() method of the Element interface returns the string value of the specified namespaced attribute of the specified element. It returns null if the element doesn't have an attribute with the given name in the namespace.

If you are working with HTML documents and you don't need to specify the requested attribute as being part of a specific namespace, use the Element.getAttribute() method instead.

Syntax

getAttributeNS(namespace, localName)

Parameters

  • namespace
    • : A string specifying the namespace of the attribute, or null for no explicit namespace.
  • localName
    • : A string specifying the name of the attribute.

Return value

A string containing the attribute's value, or null if the element doesn't have an attribute with the given name.

Examples

The following SVG document reads the value of the foo attribute in a custom namespace.

<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>

In an HTML document, the attribute has to be accessed with test:foo since namespaces are not supported.

<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>
const ns = "http://www.example.com/2014/test";
const circle = document.getElementById("target");
console.log(`Attribute value: ${circle.getAttribute("test:foo")}`);

Specifications

Browser compatibility

See also

  • Element.hasAttributeNS()
  • Element.setAttributeNS()
  • Element.removeAttributeNS()

来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
MDN Web Docs / Mozilla 贡献者
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 2.5

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。