HTML DOM className Property
Example
Set the class for a <div> element with id="myDIV":
More "Try it Yourself" examples below.
Definition and Usage
The className property sets or returns the class name of an element (the value of an element's class attribute).
Tip: A similar property to className is the classList property.
Browser Support
Property | |||||
---|---|---|---|---|---|
className | Yes | Yes | Yes | Yes | Yes |
Syntax
Return the className property:
Set the className property:
Property Values
Value | Description |
---|---|
class | Specifies the class name of an element. To apply multiple classes, separate them with spaces, like "test demo" |
Technical Details
Return Value: | A String, representing the class, or a space-separated list of classes, of an element |
---|
More Examples
Example
Get the class name of the first <div> element in the document (if any):
The result of x will be:
Example
Other examples on how to get the class name of an element:
var y = document.getElementById("myDIV").className;
Example
Get the class names of an element with multiple classes:
var x = document.getElementById("myDIV").className;
The result of x will be:
Example
Overwriting an existing class name with a new one:
document.getElementById("myDIV").className = "newClassName";
Example
To add a class to an element, without overwriting existing values, insert a space and the new class name:
Example
If there's a class of "mystyle" in an element with id="myDIV", change its font-size:
if (x.className === "mystyle") {
x.style.fontSize = "30px";
}
Example
Toggle between two class names. This example looks for a "mystyle" class in <div>, and if it exist, it will be overwritten by "mystyle2":
var x = document.getElementById("myDIV");
// If "mystyle" exist, overwrite it with "mystyle2"
if (x.className === "mystyle") {
x.className = "mystyle2";
} else {
x.className = "mystyle";
}
}
Example
Toggle between class names on different scroll positions - When the user scrolls down 50 pixels from the top, the class name "test" will be added to an element (and removed when scrolled up again).
function myFunction() {
if (document.body.scrollTop > 50) {
document.getElementById("myP").className = "test";
} else {
document.getElementById("myP").className = "";
}
}
Related Pages
CSS Tutorial: CSS Selectors
CSS Reference: CSS .class Selector
HTML DOM Reference: HTML DOM classList Property
HTML DOM Reference: HTML DOM getElementsByClassName() Method
HTML DOM Reference: HTML DOM Style Object
Element Object