定義と使い方
removeAttribute()関数は、DOM要素から引数で指定した属性を削除する関数です。
要素に指定した属性が存在しない場合は、エラーを発生させず、何も行いません。
構文
element.removeAttribute(attributeName)
引数
attributeName |
必須。要素から削除する属性の名前(文字列形式)です。 |
|---|
引数は必須のため、指定しないとエラーが発生しますが、引数で指定した属性が要素に存在しない場合でも、エラーを発生させず、何も行いません。
戻り値
ありません。つまり、undefinedを返します。
基本例
<style>
.bg {
background-color: yellowgreen;
}
</style>
<p class="bg">背景色を削除してみてください。</p>
<button type="button">背景色を削除</button>
const elem = document.querySelector("p");
const button = document.querySelector("button");
button.addEventListener("click", () => { // ボタンのクリックイベント
/* ボタンをクリックすると、
p要素のclass属性が削除されます。 */
elem.removeAttribute("class");
});
コードの補足説明querySelector()関数は、指定したCSSセレクタと一致する最初の要素オブジェクトを返します。
「背景色を削除」ボタンをクリックしてみてください!
背景色を削除してみてください。
ブール属性(Boolean attribute)の削除
removeAttribute()関数でこのようなブール属性(Boolean attribute)を削除すると、その属性が提供する機能も無効になります。
例
<input type="text" value="Hello World!" disabled>
<button type="button">有効にする</button>
const input = document.querySelector("input");
const button = document.querySelector("button");
button.addEventListener("click", () => {
input.removeAttribute("disabled");
});
「有効にする」ボタンをクリックして、テキスト入力ボックスが再び有効になるか確認してみてください。
ブラウザーの互換性
| メソッド |
デスクトップ Chrome
|
デスクトップ Edge
|
デスクトップ Firefox
|
Safari
|
|---|---|---|---|---|
removeAttribute()
|
1 | 12 | 1 | 1 |
仕様書
| 仕様書 | |
|---|---|
removeAttribute()
|
DOM Standard #ref-for-dom-element-removeattribute① |