JavaScript | DOM 操作:属性操作 – setAttribute

JavaScript
スポンサーリンク

setAttribute とは何か

setAttribute は、要素の「属性(attr)」に文字列の値を設定するためのメソッドです。href、title、alt、aria-、data- など、HTML 上のあらゆる属性を“文字列として”安全に更新できます。ここが重要です:属性は最終的に文字列で扱われます。数値や真偽値も、設定前に意図通りの文字列へ変換してから渡す癖を付けると、表示や挙動の事故を防げます。


基本の使い方(属性名と値を渡す)

文字列をそのまま設定する

<a id="link">ヘルプ</a>
<script>
  const a = document.getElementById("link");
  a.setAttribute("href", "/help");
  a.setAttribute("title", "ヘルプへ移動"); // 文字列として設定
</script>
HTML

setAttribute は、既存の値があれば上書きし、なければ新しく属性を作ります。ここが重要です:値は常に文字列。変換が必要なら String(…) で明示します。

数値や null/undefined の安全な文字列化

const btn = document.createElement("button");
btn.setAttribute("data-count", String(0));           // "0"(falsyでも保持)
btn.setAttribute("data-note", String(null));         // "null" → 意図しないことが多い
btn.setAttribute("data-note", String(null ?? ""));   // "" に丸めるのが安全
JavaScript

ここが重要です:null/undefined をそのまま文字列化すると “null”/”undefined” が表示されがち。空文字へ丸めるか、意味のある既定値に揃える方針を決めておきます。


属性とプロパティの違い(現在値はプロパティ、初期・メタは属性)

value と checked の扱いを間違えない

<input id="name" value="初期">
<script>
  const el = document.getElementById("name");
  el.setAttribute("value", "初期値の更新"); // 属性(初期値)を書き換え
  el.value = "現在の値";                    // プロパティ(現在値)を更新
</script>
HTML

フォームの「今の入力値」はプロパティ(el.value)が正解です。ここが重要です:getAttribute/setAttribute は“属性文字列”を扱うため、現在値の操作には向きません。checked/disabled などの現在のオン/オフもプロパティ(el.checked/el.disabled)を使います。

URL の違い(相対 vs 絶対)

<a id="about">About</a>
<script>
  const a = document.getElementById("about");
  a.setAttribute("href", "/about"); // 属性:そのまま文字列
  console.log(a.href);              // プロパティ:絶対URLに解決される
</script>
HTML

ここが重要です:書き込みは属性で十分、読み取りは用途に応じて属性(そのままの文字)かプロパティ(絶対URL)を選びます。


boolean 属性の正しい設定(値ではなく“有無”で管理)

disabled・checked・required などは存在が真

<input id="agree" type="checkbox">
<script>
  const el = document.getElementById("agree");

  // 悪い例:文字列で false を入れても“存在する”ので真扱い
  el.setAttribute("disabled", "false"); // 実際は無効になる(付いてしまうため)
  
  // 正しい例:有無で管理する
  el.removeAttribute("disabled");       // 外す
  el.setAttribute("disabled", "");      // 付ける(値は空でも可)

  // もっと安全:toggleAttribute を使う
  el.toggleAttribute("disabled", true);  // 付ける
  el.toggleAttribute("disabled", false); // 外す
</script>
HTML

ここが重要です:boolean 属性は“付くか付かないか”がすべて。”false” という文字を入れても付いた扱いになります。toggleAttribute/removeAttribute を使うと事故が減ります。


data-* と JSON(複合データは文字列化して持つ)

オブジェクトや配列は JSON.stringify/parse のペアで

<button id="item">購入</button>
<script>
  const btn = document.getElementById("item");
  const payload = { id: 42, tags: ["new", "sale"] };

  btn.setAttribute("data-payload", JSON.stringify(payload)); // 文字列で保存

  const raw = btn.getAttribute("data-payload") ?? "{}";
  const parsed = JSON.parse(raw); // 取り出すときにパース
</script>
HTML

ここが重要です:data-* は文字列専用。複合データは毎回 JSON のペアで扱うと、一貫して安全です。


URL・クエリは必ずエンコード(文字列結合の事故を防ぐ)

encodeURIComponent と URLSearchParams を使う

<a id="search">検索</a>
<script>
  const a = document.getElementById("search");
  const q = "赤い 果物&人気";
  const params = new URLSearchParams({ q, page: 1 });
  a.setAttribute("href", `/find?${params}`); // 正しく文字列化される
</script>
HTML

ここが重要です:ユーザー入力を URL に混ぜるとき、未エンコードのまま結合しない。URLSearchParams なら安全・確実に文字列化できます。


style 属性と getComputedStyle(用途の切り分け)

インライン CSS を直接入れるか、最終値を読むか

<div id="panel"></div>
<script>
  const p = document.getElementById("panel");
  p.setAttribute("style", "color: red; background: #eee;"); // まとめてインライン設定

  const cs = getComputedStyle(p);
  console.log(cs.color); // "rgb(255, 0, 0)"(最終的な見え方)
</script>
HTML

ここが重要です:style 属性の文字列は“直書き”だけ。見た目の最終値は getComputedStyle。設定は style プロパティ(p.style.color = “red”)の方が型安全で書きやすい場面が多いです。


安全性と標準化(ユーティリティで事故を減らす)

null/undefined 丸めと boolean 属性の一元化

function toAttrString(v, fallback = "") {
  return v == null ? fallback : String(v);
}

function setBoolAttr(el, name, on) {
  el.toggleAttribute(name, !!on);
}

// 使い方
const btn = document.querySelector("#buy");
btn.setAttribute("data-sku", toAttrString(12345));
btn.setAttribute("title", toAttrString(null, "購入ボタン"));
setBoolAttr(btn, "disabled", false); // 外す
setBoolAttr(btn, "disabled", true);  // 付ける
JavaScript

ここが重要です:文字列化と boolean 管理を“毎回同じ挙動”にする。ユーティリティ化でプロジェクト全体の安全性が上がります。


実践例:安全なリンク生成と ARIA 同期

動的リンクを安全に作り、アクセシビリティ属性も揃える

<a id="doc" class="btn">ドキュメント</a>
<script>
  const doc = document.getElementById("doc");

  function setLink(el, base, params, label) {
    const qs = new URLSearchParams(params);
    el.setAttribute("href", `${base}?${qs}`);
    el.setAttribute("title", toAttrString(label, "リンク"));
    el.setAttribute("aria-label", toAttrString(label, "リンク"));
  }

  setLink(doc, "/docs", { q: "使い方", lang: "ja" }, '検索 "使い方"');
</script>
HTML

ここが重要です:表示(title/aria-label)も属性で安全に文字列化。URL は URLSearchParams で文字列結合ミスを根絶します。


まとめ

setAttribute は「属性の文字列値」を安全に設定する基本メソッドです。値は必ず文字列化し、null/undefined は既定値へ丸める。boolean 属性は値ではなく“有無”で管理し、必要なら toggleAttribute/removeAttribute を使う。複合データは JSON で data-* に持ち、URL は URLSearchParams で正しく文字列化。現在値が欲しい場面(フォームや状態)はプロパティで扱う。小さなユーティリティで標準化すれば、初心者でも意図通りで壊れにくい属性操作が書けます。

タイトルとURLをコピーしました