Element: className プロパティ

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

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

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

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

メモ

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

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

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

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

仕様書

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

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
className

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
Has more compatibility info.

関連情報