属性の取得/設定の基本 — el.getAttribute('data-x') と el.setAttribute('data-x', v)
HTML要素の「属性」(id, class, href, src, data-xxx など)を JavaScript から読み書きする方法です。存在しない属性を getAttribute で読むと null が返ります。setAttribute は新規追加も更新もできます。
基本の使い方とポイント
<a id="link" href="/home" data-user="42">ホーム</a>
<script>
const el = document.getElementById("link");
// 取得
const href = el.getAttribute("href"); // "/home"
const userId = el.getAttribute("data-user"); // "42"(文字列)
// 設定(新規・上書き)
el.setAttribute("href", "/dashboard");
el.setAttribute("data-role", "admin");
// 存在しない属性は null
console.log(el.getAttribute("data-missing")); // null
</script>
HTML- 属性取得:
getAttribute(name)。ない場合はnull。値は文字列として返ります。 - 属性設定:
setAttribute(name, value)。既存を更新、無ければ作成。hrefやsrcの更新にも使えます。
data-属性の実用パターン
<div id="item" data-id="123" data-state="new"></div>
<script>
const item = document.getElementById("item");
// 読み取り
const id = item.getAttribute("data-id"); // "123"
const state = item.getAttribute("data-state"); // "new"
// 書き込み
item.setAttribute("data-state", "done");
// 例: クリックで状態トグル
item.addEventListener("click", () => {
const s = item.getAttribute("data-state");
item.setAttribute("data-state", s === "done" ? "new" : "done");
});
</script>
HTML- data-xxx: カスタムデータの受け渡しに最適。文字列でやり取りし、必要なら数値に変換して使います。
よく使うテンプレート集
- リンクの動的切り替え
- 効果:
hrefの動的変更でナビゲーションを制御できます。
- 効果:
const a = document.querySelector("a");
a.setAttribute("href", "https://example.com"); // 移動先変更
console.log(a.getAttribute("href")); // 確認
JavaScript- 画像の差し替え
- 効果:
srcとaltを更新して表示内容を切り替えます。
- 効果:
const img = document.querySelector("img#main");
img.setAttribute("src", "/images/02.jpg");
img.setAttribute("alt", "新しい画像");
JavaScript- 存在チェックと初期化
- 効果: 未設定時に既定値を入れて安定化します。
const v = el.getAttribute("data-x");
if (v === null) el.setAttribute("data-x", "default");
JavaScript実務でのコツ
- ラベル: 文字列として返る
getAttributeは常に文字列(またはnull)。数値や真偽値が必要なら自分で変換する。
- ラベル: 直接プロパティとの使い分け
el.id,el.className,el.href,el.srcのように「DOMプロパティ」で扱う方が自然なケースもあります。カスタムはdata-xxxとgetAttribute/setAttributeが相性良い。
- ラベル: 更新は上書き
setAttributeは値をそのまま文字列で上書きする。配列やオブジェクトを入れたい場合は JSON 文字列化が定番。
ありがちなハマりポイントと対策
- ラベル: 属性が存在せず
null- 取得時に
nullを前提に分岐。必要なら初期値をsetAttributeで入れる。
- 取得時に
- ラベル: クラスやスタイルは専用APIが便利
- クラスは
classList.add/remove/toggle、スタイルはel.styleの方が安全・簡単。
- クラスは
- ラベル: URL プロパティの差
el.hrefは絶対URL化されるなど挙動が異なることがある。文字列そのものを扱いたいならgetAttribute("href")を使う。
練習問題(手を動かして覚える)
<a id="go" href="/home" data-track="nav">Home</a>
<img id="pic" src="/img/01.jpg" alt="old">
<script>
const go = document.getElementById("go");
const pic = document.getElementById("pic");
// 1) href を書き換えてクリック先を変更
go.setAttribute("href", "/dashboard");
console.log("href:", go.getAttribute("href")); // "/dashboard"
// 2) data-track を未設定なら初期化
if (go.getAttribute("data-track") === null) {
go.setAttribute("data-track", "nav");
}
// 3) 画像を差し替えて alt も更新
pic.setAttribute("src", "/img/02.jpg");
pic.setAttribute("alt", "new");
}
</script>
HTML直感的な指針
- 読み取りは
getAttribute、未設定ならnull。書き込みはsetAttribute。 - 標準属性は DOMプロパティでもOK、カスタムは data-属性+属性APIが鉄板。
- 値は文字列前提。必要に応じて型変換して使う。
