Element.className
構文
js
var cName = elementNodeReference.className;
elementNodeReference.className = cName;
cNameは文字列変数で、現在の要素のクラスまたは空白区切りのクラス群を表します。
例
js
let el = document.getElementById('item');
if (el.className === 'active'){
el.className = 'inactive';
} else {
el.className = 'active';
}
メモ
このプロパティでは、 className という名前が class の代わりに使用されています。
これは DOM を操作するために使用される多くの言語と "class" キーワードが競合するためです。
className は SVGAnimatedString (en-US) のインスタンスにも、 element が SVGElement であれば存在する可能性があります。 SVG 要素を扱っている場合は、要素の className は Element.getAttribute や Element.setAttribute を使用して取得したり設定したりした方がいいでしょう。しかし、その要素の class 属性が空であった場合、 Element.getAttribute は"" ではなく null を返すことに注意してください。
js
elm.setAttribute('class', elm.getAttribute('class'))
メモ: class は HTML 属性であり、 className は DOM プロパティです。
仕様書
| Specification |
|---|
| DOM Standard # ref-for-dom-element-classname① |
ブラウザーの互換性
BCD tables only load in the browser