HTML DOM Element className
Example
Set the class attribute for an element:
Get the class attribute of "myDIV":
Toggle between two class names:
element.className = "newStyle";
} else {
element.className = "myStyle";
}
More examples below.
Description
The className
property sets or returns an element's class attribute.
Syntax
Return the className property:
Set the className property:
Property Values
Separate multiple classes with spaces, like "test demo".
Return Value
More Examples
Get the class attribute of the first <div> element (if any):
Get a class attribute with multiple classes:
<p>I am myDIV.</p>
</div>
Overwrite an existing class attribute with a new one:
To add new classes, without overwriting existing values, add a space and the new classes:
if "myDIV" has a "myStyle" class, change the font size:
if (elem.className == "mystyle") {
elem.style.fontSize = "30px";
}
If you scroll 50 pixels from the top of this page, the class "test" is added:
function myFunction() {
if (document.body.scrollTop > 50) {
document.getElementById("myP").className = "test";
} else {
document.getElementById("myP").className = "";
}
}
Browser Support
element.className
is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |