Set the class for a <div> element with id="myDIV":
More "Try it Yourself" examples below.
The className property sets or returns the class name of an element (the value of an element's class attribute).
Property | |||||
---|---|---|---|---|---|
className | Yes | Yes | Yes | Yes | Yes |
Return the className property:
Set the className property:
Value | Description |
---|---|
class | Specifies the class name of an element. To apply multiple classes, separate them with spaces, like "test demo" |
Return Value: | A String, representing the class, or a space-separated list of classes, of an element |
---|
Get the class name of the first <div> element in the document (if any):
The result of x will be:
Other examples on how to get the class name of an element:
Get the class names of an element with multiple classes:
The result of x will be:
Overwriting an existing class name with a new one:
To add a class to an element, without overwriting existing values, insert a space and the new class name:
If there's a class of "mystyle" in an element with id="myDIV", change its font-size:
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