1. 開発者向けのウェブ技術
  2. Web API
  3. Element
  4. attributes

このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

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 ⁨2015年7月⁩.

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

ブラウザーの互換性

関連情報

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

Help improve MDN

Learn how to contribute

This page was last modified on by MDN contributors.

AltStyle によって変換されたページ (->オリジナル) /