Element.className

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

構文

var cName = elementNodeReference.className;
elementNodeReference.className = cName;
  • cName は文字列変数で、現在の要素のクラスまたは空白区切りのクラス群を表します。

let el = document.getElementById('item');

if (el.className === 'active'){
  el.className = 'inactive';
} else {
  el.className = 'active';
}

メモ

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

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

elm.setAttribute('class', elm.getAttribute('class'))

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

仕様書

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

ブラウザーの互換性

BCD tables only load in the browser

関連情報