属性の取得(getAttribute)

「属性の取得(getAttribute)」—DOM 読み取りの要点まとめ

Element#getAttribute(name) は、要素ノードの属性値を文字列として取得するための標準メソッドです。見た目のテキストやプロパティではなく、マークアップ上の “属性” を読み取る点が重要です。


基本構文と戻り値

js
const el = document.querySelector('a.link'); const href = el.getAttribute('href'); // 例: "./about.html"
  • 引数 name は属性名(HTML では慣例として小文字を使う)。

  • 戻り値は文字列。属性が存在しない場合は null を返す(空文字 "" と区別)。

js
el.getAttribute('id'); // "main" el.getAttribute('unknown'); // null

getAttribute と “要素プロパティ” の違い

DOM には、属性(attribute)プロパティ(property) の二層があります。

対象 変化の反映
属性(マークアップ) getAttribute('value') 文字列 or null マークアップ上の値(初期値)
プロパティ(JS から触る値) input.value 型付き(文字列/数値/真偽) 現在値(ユーザー操作やスクリプトで変化)

代表例:

  • input.value: 入力中の現在値
    input.getAttribute('value'): HTML に書かれていた初期値

  • a.getAttribute('href'): 記述そのまま(相対 URL のまま)。
    a.href: ブラウザが解決した絶対 URL

  • el.getAttribute('style'): 文字列の CSS。
    el.style: CSSStyleDeclaration オブジェクト。

実務の目安

  • マークアップそのものを読みたいgetAttribute

  • 現在の状態を知りたい / 型安全に扱いたい → プロパティ(value, checked, href など)。


存在確認や関連メソッド

js
el.hasAttribute('disabled'); // 属性の有無(真偽値) el.getAttribute('disabled'); // 値(存在しなければ null) el.getAttributeNames(); // その要素が持つ全属性名の配列

空文字と null の違い

  • hasAttribute(...) === false → 属性そのものが無い

  • getAttribute(...) === "" → 属性はあるが値が空class="" など)


真偽(ブール)属性の扱い

HTML の ブール属性disabled, checked, required など)は、存在の有無で意味が決まります。

html
<input type="checkbox" checked>
js
el.hasAttribute('checked'); // true el.getAttribute('checked'); // ""(記述によっては "checked" の場合もある) el.checked; // true(プロパティは真偽値)

結論

  • ブール属性の判定は hasAttribute() か要素プロパティel.disabled 等)を使うのが安全。


data-* 属性と dataset

カスタムデータは data-* で埋め込みます。

html
<button id="buy" data-sku-id="abc-123" data-max="5"></button>
js
const btn = document.getElementById('buy'); // 1) そのまま読む btn.getAttribute('data-sku-id'); // "abc-123" // 2) dataset(ハイフンは camelCase に変換) btn.dataset.skuId; // "abc-123" btn.dataset.max; // "5"(文字列)
  • dataset は使いやすいが 文字列型。必要なら数値変換する。

  • ハイフン区切りcamelCase に変換される点に注意(data-user-namedataset.userName)。


名前空間つき属性(SVG / XML)

SVG などでは 名前空間 を持つ属性があり、getAttributeNS(ns, localName) を使う場合があります。

js
// 例: xlink:href を読む const XLINK = 'http://www.w3.org/1999/xlink'; svgUse.getAttributeNS(XLINK, 'href');
  • HTML 文脈の通常属性は getAttribute で十分。

  • XML/SVG では 大文字小文字が区別される点にも注意。


ケース感度と正規化の注意

  • HTML 属性名は ASCII 範囲で 大文字小文字非区別(慣例として小文字で指定すると安全)。

  • getAttribute('href')記述どおりの文字列を返す(相対 URL のまま)。絶対 URL が欲しい場合は el.href を使う。


実用スニペット集

1) 属性の安全な読み取り(存在チェック込み)

js
function readAttr(el, name) { return el.hasAttribute(name) ? el.getAttribute(name) : null; }

2) data-* で動作を切り替える

html
<button class="action" data-action="delete" data-confirm="本当に削除しますか?"></button> <button class="action" data-action="save"></button>
js
document.querySelectorAll('.action').forEach(btn => { const action = btn.getAttribute('data-action'); // "delete" | "save" const confirmMsg = btn.getAttribute('data-confirm'); // null か 文字列 btn.addEventListener('click', () => { if (confirmMsg && !window.confirm(confirmMsg)) return; if (action === 'delete') doDelete(); else if (action === 'save') doSave(); }); });

3) 相対 URL をそのまま使いたい/絶対 URL が欲しい

js
const a = document.querySelector('a.doc'); a.getAttribute('href'); // "./docs/intro.html"(記述そのまま) a.href; // "https://example.com/docs/intro.html"(絶対 URL)

4) 入力要素の “初期値” と “現在値”

html
<input id="price" value="100">
js
const input = document.getElementById('price'); input.getAttribute('value'); // "100"(HTML の初期値) input.value; // ユーザー操作等を反映した現在値

5) ブール属性(存在で判断)

html
<button id="run" disabled></button>
js
const btn = document.getElementById('run'); btn.hasAttribute('disabled'); // true btn.disabled; // true

よくある落とし穴

  1. null と空文字の取り違え
    存在しない → null、存在するが空 → ""。条件分岐で誤判定しがち。

  2. プロパティと混同
    hrefvalue は、今の状態が欲しければプロパティ記述値が欲しければ getAttribute

  3. ブール属性の値比較
    getAttribute('checked') === "checked" のような比較は不安定("" の場合も)。hasAttribute またはプロパティを使う。

  4. classclassName
    getAttribute('class') は文字列、el.classList はトークン操作に便利。

  5. SVG/XML の大文字小文字
    HTML と違い ケースセンシティブ。必要に応じて getAttributeNS を使う。


まとめ

  • getAttribute(name) は属性文字列を返す。無い場合は null。

  • 現在値が欲しいならプロパティ(value, checked, href, style など)を優先。

  • ブール属性は存在で判断(hasAttribute or プロパティ)。

  • URL は getAttribute(‘href’)(記述どおり)と el.href(絶対 URL)を使い分ける。

  • data-* getAttribute と dataset の両方を使い分け可能。

ChatGPT5 生成日:2025/09/11