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①

瀏覽器相容性

另見