Element: className property
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.
TheclassName property of theElement interface gets and sets the value of theclass attributeof the specified element.
In this article
Value
A string variable representing the class or space-separated classes of the current element.
Examples
const el = document.getElementById("item");el.className = el.className === "active" ? "inactive" : "active";Notes
The nameclassName is used for this property instead ofclassbecause of conflicts with the "class" keyword in many languages which are used tomanipulate the DOM.
className can also be an instance ofSVGAnimatedString iftheelement is anSVGElement. It is easier to get/set theclass attribute of an element usingElement.getAttribute andElement.setAttribute if you are dealing with SVG elements. However, takeinto account thatElement.getAttribute returnsnullinstead of"" if theelement has an emptyclass attribute.
elm.setAttribute("class", "my-class");const myClass = elm.getAttribute("class");Note:class is the name of anHTML Attribute, whileclassName is the name of aDOM Property.
Specifications
| Specification |
|---|
| DOM> # ref-for-dom-element-classname①> |
Browser compatibility
Loading…