属性の取得・変更

getAttribute setAttribute dataset

HTML属性をJavaScriptから読み取り・変更する方法です。カスタムデータ属性(data-*)の活用も重要なパターンです。

デモ:属性の取得・変更

href 属性を変更:

現在の href: https://example.com

disabled 属性の制御:

data-* カスタム属性:

コード例

js
const el = document.querySelector('a');

// 属性の取得
el.getAttribute('href');        // "https://example.com"
el.getAttribute('class');       // "link active"

// 属性の設定
el.setAttribute('href', '/new-page');
el.setAttribute('target', '_blank');

// 属性の削除
el.removeAttribute('disabled');

// 属性の存在確認
el.hasAttribute('hidden');      // true / false

// data-* カスタム属性(dataset)
// HTML: <div data-user-id="42" data-role="admin">
const div = document.querySelector('[data-user-id]');
div.dataset.userId;             // "42"  (ケバブ→キャメル変換)
div.dataset.role;               // "admin"
div.dataset.newProp = 'value';  // data-new-prop="value" が設定される
delete div.dataset.role;        // 属性を削除

重要:プロパティ vs 属性の違い

DOMプロパティ(el.value)と HTML属性(el.getAttribute("value"))は別物です。

js
// input要素の例
// HTML: <input type="text" value="初期値">
const input = document.querySelector('input');

// ユーザーが "新しい値" と入力した後...
input.value;                    // "新しい値"(現在の状態)
input.getAttribute('value');    // "初期値"(HTML属性の初期値)

// checkbox の場合
input.checked;                  // 現在のチェック状態(プロパティ)
input.getAttribute('checked');  // "checked" or null(初期値)

// 結論:現在の状態はプロパティで取得、
//       初期値やHTMLを操作したい場合はgetAttribute

NEWElement.ariaLabel など ARIAプロパティ(直接アクセス)

従来は setAttribute("aria-*") で操作していたARIA属性を、直接プロパティとして読み書きできます。

js
const btn = document.querySelector('button');

// 従来の方法
btn.setAttribute('aria-expanded', 'true');
btn.getAttribute('aria-label');

// ✅ 新しい方法(直接プロパティアクセス)
btn.ariaExpanded = 'true';
btn.ariaLabel = 'メニューを閉じる';
btn.ariaHidden = 'false';
btn.ariaDisabled = 'true';

// アクセシビリティ改善に有効
// aria-live, aria-selected, aria-checked なども同様

🤖 AIプロンプトテンプレート

以下の要件を満たすTypeScript + Reactコンポーネントを作成してください。

- getAttribute/setAttribute/removeAttributeを使ったDOM属性操作のサンプルを示す
- data-*カスタム属性の取得・設定・削除の例を含める
- hasAttribute()で属性の存在チェックをするサンプルを含める
- aria-*属性を動的に変更してアクセシビリティを改善する例を示す
- 複数の属性を一括操作するユーティリティ関数のサンプルを含める
- コメントは日本語で記述する

⚠️ このプロンプトはあくまでたたき台です。AIの回答はモデルやバージョン、会話の文脈によって毎回異なります。意図通りに動かない場合は、条件を追記・修正してお使いください。