このページで解説している内容は、以下の YouTube 動画の解説で見ることができます。
【JavaScript入門】要素の属性を操作するメソッド

要素の属性を操作するメソッド
HTML 要素は id
や src
など数多くの 属性 (attribute) を持ちます。
ここまでは .style
や .id
のように“専用プロパティ”で操作する方法を紹介しましたが、すべての属性に対応したプロパティがあるわけではありません。そこで使うのが 属性操作メソッド です。getAttribute
で値を取り出し、setAttribute
で新しい値を書き込み、removeAttribute
で削除――という具合に汎用的に扱えます。

1.属性値を取得する
1.1. getAttribute(s)
指定名の値を文字列で返す。存在しなければ null
。
1.2. getAttributeNames()
その要素が持つ すべての属性名を配列 で取得。デバッグに便利。
2.属性の有無と削除
2.1. hasAttribute(s)
属性を持っているか真偽値で返す。
2.2. removeAttribute(s)
指定属性を取り除く。class
なども消えるので注意。
3.属性を設定・更新する
setAttribute(s, v)
存在しなければ新規追加、あれば上書き。数値を渡しても文字列に変換される。
4.属性操作メソッド一覧
メソッド | 戻り値 | 主な用途 |
---|---|---|
getAttribute(name) | 文字列 / null | 値を読む |
getAttributeNames() | 文字列配列 | 属性一覧を取得 |
hasAttribute(name) | true / false | あるか判定 |
removeAttribute(name) | なし | 属性を削除 |
setAttribute(name, value) | なし | 追加・更新 |
5.実践サンプル ― 画像属性を読み書き
使用する画像
painting1.png | painting2.png | painting3.png |
![]() | ![]() | ![]() |
ファイル名: attribute_demo.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>要素の属性を操作するメソッド</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
body{font-family:sans-serif;margin:2rem}
img{margin:.4rem;border:1px solid #ccc}
</style>
</head>
<body>
<h2>🎨 絵画ギャラリー</h2>
<img src="painting1.png" alt="絵画1">
<img src="painting2.png" alt="絵画2">
<img src="painting3.png" alt="絵画3">
<pre id="log"></pre>
<script>
// すべての <img> を取得
const imgs = document.querySelectorAll('img');
const lines = [];
// ループで属性を操作
imgs.forEach(img => {
// 1) src を取得してログへ
const url = img.getAttribute('src');
lines.push(`src = ${url}`);
// 2) 高さを 150px に設定
img.setAttribute('height', 150);
// 3) alt が無い場合だけ追加
if (!img.hasAttribute('alt')) {
img.setAttribute('alt', 'no title');
}
// 4) title 属性があれば削除
if (img.hasAttribute('title')) {
img.removeAttribute('title');
}
});
// 5) 最初の画像の属性名一覧を表示
lines.push('属性名一覧:', imgs[0].getAttributeNames().join(', '));
// 結果を <pre> に表示
document.getElementById('log').textContent = lines.join('\n');
</script>
</body>
</html>
ブラウザ表示
3 枚の画像が 200 px の高さで並び、下部のログに src = …
と属性名一覧が出力されます。

コード解説
- 取得:
getAttribute('src')
で URL を文字列取得。 - 設定:
setAttribute('height', 200)
で数値を渡しても自動で'150'
に変換。 - 判定:
hasAttribute('alt')
で代替テキストの有無をチェック。 - 削除: 不要な
title
があればremoveAttribute('title')
で削除。 - 列挙:
getAttributeNames()
は配列で返るためjoin(', ')
で整形。
まとめ
- get / set / remove / has の 4 操作を覚えれば、あらゆる属性を動的に制御できる。
- CSS で扱うカスタムデータ属性(
data-*
)も同じメソッドで操作可能。 - プロパティが用意されていない特殊属性や ARIA 属性は、これら汎用メソッドでアクセスするのが確実。
これらのメソッドを駆使して、静的な HTML をインタラクティブなアプリへ進化させましょう。