DOM を操作する際、HTML 要素に設定された属性の値を取得したい場面は頻繁にあります。リンクの href、画像の src、フォーム要素の disabled、カスタムの data-* 属性など、JavaScript の getAttribute メソッドを使えばどの属性でも文字列として取得できます。
・getAttribute の基本構文と戻り値
・標準属性(href / src / class など)の取得
・data-* 属性の取得と dataset との使い分け
・getAttribute と DOM プロパティの違い
・hasAttribute で属性の存在を判定する方法
・setAttribute / removeAttribute で属性を設定・削除する方法
・フォーム制御やアクセシビリティ操作の実務パターン
getAttribute の基本構文と戻り値
getAttribute は Element オブジェクトのメソッドで、引数に属性名を渡すと対応する値を文字列で返します。
const value = element.getAttribute(attributeName); // attributeName: 取得したい属性名(文字列) // 戻り値: 属性の値(文字列)または null
属性が存在する場合は値が文字列として返り、存在しない場合は null が返ります。空文字で設定されている属性は空文字 "" が返る点に注意してください。
<a id="myLink" href="/about" class="nav-link" data-section="company">会社概要</a>
const link = document.getElementById("myLink");
console.log(link.getAttribute("href")); // "/about"
console.log(link.getAttribute("class")); // "nav-link"
console.log(link.getAttribute("data-section")); // "company"
console.log(link.getAttribute("target")); // null(属性なし)
getAttribute("CLASS") と getAttribute("class") は同じ結果を返します。ただしコードの可読性のため、小文字で統一するのが一般的です。標準属性を取得する実例
よく使われる標準属性を getAttribute で取得する例をまとめます。
<img id="logo" src="/images/logo.png" alt="ロゴ" width="200"> <input id="email" type="email" name="user_email" placeholder="メールアドレス" required> <a id="extLink" href="https://example.com" target="_blank" rel="noopener">外部リンク</a>
const img = document.getElementById("logo");
console.log(img.getAttribute("src")); // "/images/logo.png"
console.log(img.getAttribute("alt")); // "ロゴ"
console.log(img.getAttribute("width")); // "200"(文字列)
const input = document.getElementById("email");
console.log(input.getAttribute("type")); // "email"
console.log(input.getAttribute("name")); // "user_email"
console.log(input.getAttribute("placeholder")); // "メールアドレス"
const extLink = document.getElementById("extLink");
console.log(extLink.getAttribute("target")); // "_blank"
console.log(extLink.getAttribute("rel")); // "noopener"
width="200" の場合も "200"(文字列)です。数値として扱いたい場合は Number(img.getAttribute("width")) のように変換が必要です。getAttribute と DOM プロパティの違い
要素の属性値は getAttribute("href") のようにメソッドで取得する方法と、element.href のようにプロパティで直接アクセスする方法があります。多くの場合は同じ結果になりますが、一致しないケースがあるため違いを正確に理解しておくことが重要です。
| 比較項目 | getAttribute() | DOM プロパティ |
|---|---|---|
| 戻り値の型 | 常に文字列(または null) | 属性に応じた型(文字列・真偽値・数値など) |
| href の値 | HTML に書かれた値そのまま | 完全な URL に解決された値 |
| checked / disabled | "checked"・"" などの文字列 |
true / false(真偽値) |
| class | getAttribute("class") |
element.className または classList |
| style | インラインスタイル文字列 | CSSStyleDeclaration オブジェクト |
| カスタム属性 | 取得できる | プロパティとしては存在しない |
href で結果が変わる具体例
<a id="relLink" href="/about">About</a>
const link = document.getElementById("relLink");
// getAttribute: HTMLに書かれた値そのまま
console.log(link.getAttribute("href")); // "/about"
// DOM プロパティ: 完全なURLに解決される
console.log(link.href); // "https://example.com/about"
checked で結果が変わる具体例
<input id="agree" type="checkbox" checked>
const cb = document.getElementById("agree");
// getAttribute: HTML属性の初期値
console.log(cb.getAttribute("checked")); // ""(空文字列)
// DOM プロパティ: 現在の状態(真偽値)
console.log(cb.checked); // true
// ユーザーがチェックを外した後
cb.checked = false;
console.log(cb.getAttribute("checked")); // "" (HTML属性は変わらない)
console.log(cb.checked); // false(現在の状態を反映)
data-* 属性の取得と dataset との比較
HTML5 で導入された data-* 属性(カスタムデータ属性)は、要素に独自のデータを埋め込む標準的な方法です。getAttribute でも取得できますが、dataset プロパティを使う方法もあります。
<div id="product"
data-product-id="12345"
data-price="1980"
data-in-stock="true"
data-category-name="electronics">
商品カード
</div>
const el = document.getElementById("product");
console.log(el.getAttribute("data-product-id")); // "12345"
console.log(el.getAttribute("data-price")); // "1980"
console.log(el.getAttribute("data-in-stock")); // "true"
console.log(el.getAttribute("data-category-name")); // "electronics"
const el = document.getElementById("product");
// ケバブケース → キャメルケースに自動変換
console.log(el.dataset.productId); // "12345"
console.log(el.dataset.price); // "1980"
console.log(el.dataset.inStock); // "true"
console.log(el.dataset.categoryName); // "electronics"
| 比較項目 | getAttribute(“data-xxx”) | element.dataset.xxx |
|---|---|---|
| 属性名の指定 | ケバブケースそのまま | キャメルケースに変換 |
| 戻り値 | 文字列 or null | 文字列 or undefined |
| 書き込み | setAttribute で設定 | 直接代入で設定可能 |
| 一覧取得 | 不可 | Object.keys(el.dataset) で全キー取得 |
| ブラウザ対応 | IE6+ | IE11+ |
dataset を使う方が簡潔で読みやすいです。getAttribute は data-* 以外のカスタム属性や、古いブラウザへの対応が必要な場合に使います。hasAttribute で属性の存在を判定する
属性が存在するかどうかを調べるには hasAttribute メソッドを使います。getAttribute の戻り値で null チェックする方法もありますが、hasAttribute の方が意図が明確です。
<button id="submitBtn" disabled>送信</button> <input id="nameInput" type="text" value="">
const btn = document.getElementById("submitBtn");
const input = document.getElementById("nameInput");
// hasAttribute: 属性の有無を true/false で返す
console.log(btn.hasAttribute("disabled")); // true
console.log(btn.hasAttribute("hidden")); // false
// getAttribute での null チェックでも同じ判定は可能
console.log(btn.getAttribute("disabled") !== null); // true
// 空文字の value 属性: 存在はしている
console.log(input.hasAttribute("value")); // true
console.log(input.getAttribute("value")); // ""(空文字)
disabled・checked・readonly・required など)は、値がなくても属性が存在するだけで有効です。getAttribute("disabled") は "" を返すことがあるため、存在チェックには hasAttribute を使いましょう。setAttribute で属性を設定する
属性を新規追加または上書きするには setAttribute を使います。
element.setAttribute(name, value); // name: 属性名(文字列) // value: 設定する値(文字列に変換される)
const link = document.createElement("a");
// 属性を設定
link.setAttribute("href", "/contact");
link.setAttribute("class", "btn btn-primary");
link.setAttribute("target", "_blank");
link.setAttribute("rel", "noopener noreferrer");
link.setAttribute("data-action", "navigate");
console.log(link.getAttribute("href")); // "/contact"
console.log(link.getAttribute("class")); // "btn btn-primary"
// 既存の属性を上書き
link.setAttribute("href", "/about");
console.log(link.getAttribute("href")); // "/about"
removeAttribute で属性を削除する
不要になった属性を削除するには removeAttribute を使います。存在しない属性を指定してもエラーにはなりません。
const btn = document.querySelector("#submitBtn");
// disabled 属性を削除 → ボタンが有効になる
btn.removeAttribute("disabled");
console.log(btn.hasAttribute("disabled")); // false
// 存在しない属性を削除してもエラーにならない
btn.removeAttribute("data-nonexistent"); // 何も起きない
| メソッド | 用途 | 注意点 |
|---|---|---|
getAttribute(name) |
属性値を取得 | 存在しない場合は null |
setAttribute(name, value) |
属性を追加・上書き | 値は文字列に変換される |
removeAttribute(name) |
属性を削除 | 存在しない属性でもエラーなし |
hasAttribute(name) |
属性の存在を判定 | Boolean 属性のチェックに最適 |
実務でよく使うパターン
フォーム要素の disabled を動的に切り替える
入力内容に応じてボタンの有効・無効を切り替える実装です。
const input = document.getElementById("username");
const btn = document.getElementById("submitBtn");
input.addEventListener("input", () => {
if (input.value.trim().length > 0) {
btn.removeAttribute("disabled");
} else {
btn.setAttribute("disabled", "");
}
});
アクセシビリティ属性(ARIA)を操作する
アコーディオンやモーダルでは ARIA 属性を動的に切り替えることで、スクリーンリーダーに状態を正しく伝えられます。
function toggleAccordion(header) {
const content = header.nextElementSibling;
const isOpen = header.getAttribute("aria-expanded") === "true";
// 開閉状態を反転
header.setAttribute("aria-expanded", String(!isOpen));
content.setAttribute("aria-hidden", String(isOpen));
// 表示切り替え
content.style.display = isOpen ? "none" : "block";
}
複数要素から特定の data-* 属性でフィルタリングする
商品一覧やカードリストで、特定のカテゴリに該当する要素だけを表示する実装です。
function filterByCategory(category) {
const cards = document.querySelectorAll(".product-card");
cards.forEach(card => {
const cardCategory = card.getAttribute("data-category");
if (category === "all" || cardCategory === category) {
card.style.display = "block";
} else {
card.style.display = "none";
}
});
}
// 使用例
filterByCategory("electronics");
動的に画像の src を切り替える
const img = document.getElementById("mainImage");
// サムネイルクリックでメイン画像を切り替え
document.querySelectorAll(".thumbnail").forEach(thumb => {
thumb.addEventListener("click", () => {
const fullSrc = thumb.getAttribute("data-full-src");
img.setAttribute("src", fullSrc);
img.setAttribute("alt", thumb.getAttribute("alt"));
});
});
関連メソッドとの使い分け
DOM の属性操作・要素取得に関連する記事も参考にしてください。
- querySelector / querySelectorAll の使い方 — CSS セレクタで要素を取得する方法
- classList の使い方完全ガイド — クラス属性の操作に特化した API
- name 属性で要素を取得する方法 — フォーム要素の name 属性活用
- HTML 要素を追加・削除する方法 — DOM ノードの操作全般
- 兄弟要素を取得する方法 — nextElementSibling で隣接要素にアクセス
よくある質問
DOM プロパティの方が型が正確で簡潔です。getAttribute は HTML に記述された生の値が必要な場合(相対パスそのまま取得したいなど)や、カスタム属性の取得に使います。dataset の方が推奨です。data-user-id="1" は el.dataset.userId で取得できます(ケバブケース → キャメルケース自動変換)。getAttribute でも同じ値を取れますが、dataset の方が読みやすく、Object.keys(el.dataset) で全キーの一覧も取れます。null が返ります(空文字列ではありません)。属性の有無を確認するなら hasAttribute の方が意図が明確です。el.setAttribute("disabled", "") のように空文字を値として渡します。Boolean 属性は値の内容に関係なく、属性が存在するだけで有効になります。削除する場合は removeAttribute("disabled") を使います。まとめ
getAttribute は HTML 要素の属性値を文字列として取得するシンプルなメソッドです。setAttribute で設定、removeAttribute で削除、hasAttribute で存在チェックと組み合わせることで、DOM の属性操作を自在にコントロールできます。
ポイントはDOM プロパティとの使い分けです。標準属性の現在の状態を扱うなら DOM プロパティ、HTML に記述された生の値やカスタム属性を扱うなら getAttribute が適しています。data-* 属性については dataset プロパティの方が簡潔に書けるため、状況に応じて使い分けてください。

