setAttribute と getAttribute
setAttribute と getAttribute は、要素の属性を操作するための基本メソッドです。どんな属性でも汎用的に扱えます。
getAttribute で属性を取得
<a id="link" href="https://example.com" target="_blank">リンク</a>const link = document.getElementById('link');
console.log(link.getAttribute('href')); // "https://example.com"
console.log(link.getAttribute('target')); // "_blank"
console.log(link.getAttribute('title')); // null(存在しない)setAttribute で属性を設定
const link = document.getElementById('link');
link.setAttribute('href', 'https://google.com');
link.setAttribute('title', '新しいタイトル');
link.setAttribute('rel', 'noopener');属性を削除する
removeAttribute で属性を削除できます。
link.removeAttribute('target');属性の存在チェック
hasAttribute で属性が存在するかを確認できます。
if (link.hasAttribute('target')) {
console.log('target 属性があります');
}プロパティとの違い
HTML 属性と DOM プロパティは似ていますが、違いがあります。
getAttribute/setAttribute
HTML 属性を操作。常に文字列
プロパティ(element.href など)
DOM プロパティを操作。型が保持される
const checkbox = document.querySelector('input[type="checkbox"]');
// 属性は文字列
checkbox.setAttribute('checked', 'checked');
console.log(checkbox.getAttribute('checked')); // "checked"
// プロパティは boolean
checkbox.checked = true;
console.log(checkbox.checked); // true実際に動かしてみよう
HTML
CSS
JavaScript
<img id="image" src="" alt="画像">
<br>
<button id="cat">猫に変更</button>
<button id="dog">犬に変更</button>#image {
width: 150px;
height: 150px;
object-fit: cover;
border: 2px solid #ddd;
}const img = document.getElementById('image');
document.getElementById('cat').addEventListener('click', () => {
img.setAttribute('src', 'https://placekitten.com/150/150');
img.setAttribute('alt', '猫の画像');
});
document.getElementById('dog').addEventListener('click', () => {
img.setAttribute('src', 'https://placedog.net/150/150');
img.setAttribute('alt', '犬の画像');
});よく使う属性操作
// disabled の切り替え
button.setAttribute('disabled', ''); // 無効化
button.removeAttribute('disabled'); // 有効化
// hidden の切り替え
element.setAttribute('hidden', ''); // 非表示
element.removeAttribute('hidden'); // 表示
// aria 属性
element.setAttribute('aria-label', '説明文');
element.setAttribute('aria-hidden', 'true');標準的な属性(href、src、value など)はプロパティでも操作できますが、カスタム属性や aria 属性などは setAttribute / getAttribute を使うのが確実です。