DOM

ドキュメント オブジェクト モデル

Element.getAttributeNS() メソッド

 編集:2022.09.21 by T.A.

[Edge]。→mdn

element の指定された名前空間の名前を持つ指定属性の値を文字列で返します。

該当が無い場合は null または ""(空文字列)のどちらかを返します。詳しくはメモを参照してください。

構文
element.getAttributeNS(namespace, attrName)
element Element
namespace 名前空間を特定する文字列です。
attrName 属性の名前を指定する文字列です。
戻り値

指定された属性の値を表す文字列です。その属性が存在しない場合 null になります。

以下の SVG 文書は独自の名前空間にある foo 属性の値を読み取ります。

<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="#444"
      stroke-width="2" fill="none" test:foo="Hello namespaced attribute!"/>

  <script type="text/javascript">
    var ns = 'http://www.example.com/2014/test';
    var circle = document.getElementById( 'target' );

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

HTML5 文書では名前空間に対応していないため、この属性は test:foo でアクセスする必要があります。

<!DOCTYPE html>
<html>
<body>

<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="#444" stroke-width="2"
      fill="none" test:foo="Foo value"/>
</svg>

<script type="text/javascript">
  var ns = 'http://www.example.com/2014/test';
  var circle = document.getElementById( 'target' );
  console.log('Attribute value: ' + circle.getAttribute('test:foo'));
</script>

</body>
</html>
メモ

名前空間は XML 文書でのみ対応しています。HTML5 文書では、代わりに getAttribute() を使用する必要があります。

getAttributeNS() は getAttribute() とは異なり、特定の名前空間に属している要求された属性をより深く特定することができます。上記の例では、属性は Mozilla の架空の "specialspace" 名前空間に属しています。

¶省く


テスト
HTML:


ここにHTMLが表示される
スクリプト組み込み:
JavaScript:


JavaScript:



表示内容:
表示内容: