Element: attributes プロパティ

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Element.attributes プロパティは、そのノードに登録されたすべての属性ノードの生きたコレクションを返却します。返却される値は NamedNodeMap であり、Array ではありません。つまり、Array のメソッドは持っておらず、Attr ノードのインデックスはブラウザーによって変わる可能性があります。より正確に言うと、attributes はその属性に関するあらゆる情報を表す文字列のキーと値の組です。

NamedNodeMap オブジェクトです。

基本的な例

js
// 文書内の最初の <p> 要素を取得
const paragraph = document.querySelector("p");
const attributes = paragraph.attributes;

要素の属性を列挙する

for...of を使用すると、要素の属性をすべて列挙することができます。 次の例では、"paragraph" を id に持つ要素のすべての属性ノードを走査し、その属性の値を表示します。

html
<!DOCTYPE html>
<html lang="ja">
  <head>
    <title>属性の例</title>
    <script>
    function listAttributes() {
       const paragraph = document.getElementById("paragraph");
       const result = document.getElementById("result");

       // まず、段落に属性があるか確かめる
       if (paragraph.hasAttributes()) {
         let output = "最初の段落の属性:\n";
         for (const attr of paragraph.attributes) {
           output += `${attr.name} -> ${attr.value}\n`;
         }
         result.textContent = output;
       } else {
         result.textContent = "表示する属性はありません";
       }
    }
    </script>
  </head>

  <body>
    <p id="paragraph" style="color: green;">サンプルの段落</p>
    <form action="">
      <p>
        <input type="button" value="最初の要素の属性の名前と値"
          onclick="listAttributes();">
        <pre id="result"></pre>
      </p>
    </form>
  </body>
</html>

仕様書

Specification
DOM
# dom-element-attributes

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
attributes

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

関連情報

  • 返却される値のインターフェイスである NamedNodeMap
  • quirksmode におけるブラウザー間の互換性の考慮事項