Remove CSS properties set by JavaScript and restore the original CSS rules.
removeProperty() は、element.style などのCSS宣言から、指定したCSSプロパティだけを削除するメソッドです。
一時的に変えた見た目を解除して、CSSファイルやクラスで定義した状態へ戻したいときに使います。
JavaScript
const oldValue = element.style.removeProperty("background-color");
HTML
<button type="button" id="resetButton">背景色を戻す</button>
<div id="box" style="background-color: tomato;">色が付いた要素</div>
JavaScript
const box = document.querySelector("#box");
const resetButton = document.querySelector("#resetButton");
resetButton.addEventListener("click", () => {
const oldValue = box.style.removeProperty("background-color");
console.log(oldValue);
});
クリックすると、style 属性内の background-color だけが消えます。
引数には、JavaScriptのプロパティ名ではなくCSSのプロパティ名を渡します。
JavaScript
box.style.removeProperty("background-color");
誤った指定例です。
JavaScript
box.style.removeProperty("backgroundColor");
backgroundColor の形ではなく、background-color の形で書きます。
getComputedStyle() は計算後の値を読むためのものなので、変更対象にしません。NoModificationAllowedError が発生することがあります。フォームのエラー色、選択中の強調表示、ユーザー操作後の一時的なスタイルを解除するときに使います。
JavaScript
const message = document.querySelector("#message");
message.style.setProperty("color", "red");
message.style.removeProperty("color");
removeProperty() はCSSOMのAPIです。undefined ではありません。font-size のようにハイフン付きで渡します。style.backgroundColor = ""; でもインライン指定を消せますが、指定したCSS宣言を削除する意図は removeProperty() の方が明確です。removeProperty() は何を削除しますか?backgroundColor の形で指定できますか?removeProperty() の引数には、background-color のようなCSSプロパティ名を渡します。