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