【JavaScript】setAttribute / getAttribute – 基本的な使い方

JavaScriptを使ってHTML要素の属性を操作する場合、setAttribute()getAttribute()は非常に便利なメソッドです。今回は、それぞれの基本的な使い方や活用例、使用時の注意点についてまとめていきたいと思います。

setAttribute()とは?

setAttribute()は、HTML要素に新しい属性を追加したり、既存の属性の値を変更したりするためのメソッドです。

基本構文

JavaScript
element.setAttribute(name, value);
  • name:設定する属性名(文字列)
  • value:設定する属性の値(文字列)

使用例

以下は、画像要素のsrc属性とalt属性を設定する例です。

See the Pen Untitled by tones (@tonescodedesign) on CodePen.

JavaScript
const image = document.getElementById('myImage');
image.setAttribute('src', 'https://tonescodedesign.net/sample/images/coffee.jpg');
image.setAttribute('alt', 'サンプル画像');

console.log(image); // <img id="myImage" src="https://tonescodedesign.net/sample/images/coffee.jpg" alt="サンプル画像">
HTML
<img id="myImage" />

getAttribute()とは?

getAttribute()は、HTML要素から指定した属性の値を取得するためのメソッドです。

基本構文

JavaScript
element.getAttribute(name);
  • name:取得する属性名(文字列)

使用例

以下は、リンク要素のhref属性の値を取得する例です。

See the Pen setAttribute / getAttribute by tones (@tonescodedesign) on CodePen.

JavaScript
const link = document.getElementById('myLink');
const hrefValue = link.getAttribute('href');
console.log(hrefValue); // "https://example.com"
HTML
<a id="myLink" href="https://example.com">リンクテキスト</a>

setAttributeとgetAttributeの組み合わせ

これらのメソッドは、属性の値を取得して変更する場合に組み合わせて使用することができます。

ボタンのデータ属性を操作する

See the Pen Untitled by tones (@tonescodedesign) on CodePen.

JavaScript
const button = document.getElementById('myButton');

// 現在の属性値を取得
const state = button.getAttribute('data-state');
console.log(state); // "off"

// 属性値を変更
if (state === "off") {
  button.setAttribute('data-state', 'on');
  button.textContent = '状態: ON';
}
HTML
<button id="myButton" data-state="off">状態: OFF</button>

使用時の注意点

大文字小文字の区別

HTML属性は基本的に小文字として扱われますが、JavaScriptで操作する際には正確に一致させる必要があります。

JavaScript
// 正しい例
element.setAttribute('data-value', '123');

// 誤った例("DATA-VALUE"は無効)
element.setAttribute('DATA-VALUE', '123');

存在しない属性の取得

getAttribute()を使用して存在しない属性を取得しようとした場合、nullが返されます。

JavaScript
const element = document.getElementById('myElement');
console.log(element.getAttribute('nonexistent')); // null

アクセシビリティへの配慮

動的に属性を設定する際には、アクセシビリティにも配慮しましょう。

  • alt属性の設定:画像には必ずalt属性を設定し、内容を正確に記述します。(※装飾目的の画像に対しては設定する必要はありません)
  • role属性やARIA属性の使用:動的に状態を変更する要素には、適切なARIA属性を設定してスクリーンリーダーでの理解を助けます。