定義と使い方
setAttribute()関数は、DOM要素に属性の値を設定する関数です。
特徴
構文
element.setAttribute(attributeName, value)
引数
戻り値
ありません。つまり、undefinedを返します。
DOM要素から属性の値を取得するには、getAttribute()関数を使用してください。
DOM要素から特定の属性を削除するには、removeAttribute()関数を使用してください。
例
状況別の例を見てみましょう。
指定した属性がすでに存在する場合
要素に指定した属性がすでに存在する場合は、その値が更新されます。
<input type="password" value="test">
<button type="button">パスワードを表示</button>
const elem = document.querySelector("input");
const button = document.querySelector("button");
button.addEventListener("click", () => { // ボタンのクリックイベント
/* ボタンをクリックすると、
input要素のtype属性の値がpasswordからtextに変更されます。 */
elem.setAttribute("type", "text");
});
コードの補足説明querySelector()関数は、指定したCSSセレクタと一致する最初の要素オブジェクトを返します。
「パスワードを表示」ボタンをクリックしてみてください!
指定した属性が存在しない場合
<input type="text">
<button type="button">testを入力する</button>
const elem = document.querySelector("input");
const button = document.querySelector("button");
button.addEventListener("click", () => { // ボタンのクリックイベント
/* ボタンをクリックすると、
input要素にvalue属性が追加され、
値がtestに設定されます。 */
elem.setAttribute("value", "test");
});
「testを入力する」ボタンをクリックしてみてください!
複数の属性を設定する
それぞれの属性は、setAttribute()関数をそれぞれ呼び出して設定します。
const element = document.getElementById("example-id");
// 1つ目の属性を設定
element.setAttribute("alt", "Set your alt");
// 2つ目の属性を設定
element.setAttribute("title", "Set your title");
// 3つ目の属性を設定
element.setAttribute("src", "/images/image.jpg");
値を必要としないブール属性(Boolean attribute)の場合
<input type="text">
<button type="button">input boxを非表示にする</button>
const elem = document.querySelector("input");
const button = document.querySelector("button");
button.addEventListener("click", () => { // ボタンのクリックイベント
/* ボタンをクリックすると、
input要素にhidden属性を追加します。
値は空の文字列("")に設定します。 */
elem.setAttribute("hidden", "");
});
「input boxを非表示にする」ボタンをクリックしてみてください!
注意点
element.setAttribute("style", "background-color:blue;");
代わりに、JavaScriptのstyleプロパティを使用してください。
element.style.backgroundColor = "blue";
ブラウザーの互換性
| メソッド |
デスクトップ Chrome
|
デスクトップ Edge
|
デスクトップ Firefox
|
Safari
|
|---|---|---|---|---|
setAttribute()
|
1 | 12 | 1 | 1 |
仕様書
| 仕様書 | |
|---|---|
setAttribute()
|
DOM Standard #ref-for-dom-element-setattribute① |