1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【ぼくのJavaScript備忘録】Attribute の使い方徹底解説

Last updated at Posted at 2025-02-04

1. Attribute とは?

Attribute(属性)とは、HTML 要素に設定される情報のことで、例えば idclasssrcalt などが含まれます。JavaScript を使えば、要素の属性を取得・変更・削除することができます。

ポイントsetAttributegetAttributeremoveAttribute を使うと、属性を操作できる!


2. getAttribute で属性を取得

getAttribute を使うと、要素の指定した属性の値を取得できます。

☑️ 例1:画像の src を取得

const img = document.getElementById("myImage");
console.log(img.getAttribute("src"));

ID myImagesrc を取得

☑️ 例2:カスタム属性(data-*)を取得※

<button id="myButton" data-info="Taro">Click me</button>
const button = document.getElementById("myButton");
console.log(button.getAttribute("data-info")); // "Taro"

ボタンの data-info 属性の値を取得
※ただし、同じ操作をする場合、以下の方法の方が良いみたいです!
コメントでご指摘いただきました!ありがとうございます!

🔍 dataset を使ったカスタム属性の取得

カスタム属性(data-*)を取得する場合、getAttribute の代わりに dataset プロパティを使用することができます!

const button = document.getElementById("myButton");
console.log(button.dataset.info); // "Taro"

dataset を使うと、カスタム属性の値を簡単に取得でき、getAttribute よりも直感的に扱える!

メリット
・シンプルで直感的な記述
・可読性が向上し、コードの意図が明確になる
・メンテナンスしやすく、データの追加・変更が簡単

🔗 参考リンク

より詳しい情報は、MDN Web Docs の公式ページをご覧ください。
MDN Web Docs - dataset の解説


3. setAttribute で属性を変更

setAttribute を使うと、要素の属性を変更または追加できます。

☑️ 例3:リンクの href を変更

const link = document.getElementById("myLink");
link.setAttribute("href", "https://example.com");

ID myLinkhrefhttps://example.com に変更

☑️ 例4:画像の alt を追加

const img = document.getElementById("myImage");
img.setAttribute("alt", "新しい説明文");

画像の alt 属性を追加・変更


4. removeAttribute で属性を削除

removeAttribute を使うと、要素の属性を削除できます。

☑️ 例5:ボタンの disabled を削除

const button = document.getElementById("submitBtn");
button.removeAttribute("disabled");

ボタンの disabled 属性を削除し、クリックできるようにする

☑️ 例6:class を削除

const div = document.getElementById("content");
div.removeAttribute("class");

class を削除してスタイルをリセット


5. hasAttribute で属性の有無を確認

hasAttribute を使うと、特定の属性があるかどうかを確認できます。

☑️ 例7:要素に hidden 属性があるかチェック

const section = document.getElementById("mySection");
if (section.hasAttribute("hidden")) {
    console.log("hidden 属性があります");
} else {
    console.log("hidden 属性がありません");
}

要素に hidden があるかどうかを判定


6. まとめ

☑️ getAttribute("属性名") で属性の値を取得できる
☑️ setAttribute("属性名", "値") で属性を変更または追加できる
☑️ removeAttribute("属性名") で属性を削除できる
☑️ hasAttribute("属性名") で属性の有無をチェックできる

Attribute を活用して、HTML 要素を自在に操作しよう!

1
1
9

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?