Element: className プロパティ

classNameElement インターフェイスのプロパティで、この要素の class 属性の値を取得したり設定したりします。

文字列変数で、現在の要素のクラスまたは空白区切りのクラス群を表します。

js
const el = document.getElementById("item");
el.className = el.className === "active" ? "inactive" : "active";

メモ

このプロパティでは、 className という名前が class の代わりに使用されています。 これは DOM を操作するために使用される多くの言語と "class" キーワードが競合するためです。

classNameSVGAnimatedString (en-US) のインスタンスにも、elementSVGElement であれば存在する可能性があります。 SVG 要素を扱っている場合は、要素の classNameElement.getAttributeElement.setAttribute を使用して取得したり設定したりした方がいいでしょう。しかし、その要素の class 属性が空であった場合、Element.getAttribute"" ではなく null を返すことに注意してください。

js
elm.setAttribute("class", elm.getAttribute("class"));

メモ: classHTML 属性であり、 classNameDOM プロパティです。

仕様書

Specification
DOM Standard
# ref-for-dom-element-classname①

ブラウザーの互換性

BCD tables only load in the browser

関連情報