Element: className property

TheclassNameproperty of the Elementinterface gets and sets the value of theclassattribute of the specified element.

Value

A string variable representing the class or space-separated classes of the current element.

Examples

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

Notes

The nameclassNameis used for this property instead ofclass because of conflicts with the "class" keyword in many languages which are used to manipulate the DOM.

classNamecan also be an instance ofSVGAnimatedStringif theelementis anSVGElement.It is better to get/set the classNameof an element usingElement.getAttributeand Element.setAttributeif you are dealing with SVG elements. However, take into account thatElement.getAttributereturns null instead of""if theelementhas an emptyclassattribute.

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

Note:Theclassis anHTML Attribute,while the classNameis aDOM Property.

Specifications

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

Browser compatibility

BCD tables only load in the browser

See also