HTML DOM Element className property
- Previous Page classList
- Next Page click()
- Go to the Previous Level HTML DOM Elements Object
Definition and usage
className
Set or return the class attribute of the element.
See also:
Example
Example 1
Set the class attribute of the element:
element.className = "myStyle";
Example 2
Get the class attribute of "myDIV":
let value = document.getElementById("myDIV").className;
Example 3
Toggle between two class names:
if (element.className == "myStyle") { element.className = "newStyle"; } element.className = "myStyle";
Tip:More examples are provided below the page.
Syntax
Return the className property:
HTMLElementObject.className
Set the className property:
HTMLElementObject.className = class
Attribute value
Value | Description |
---|---|
class |
The class name of an element. Multiple classes are separated by spaces, such as "test demo". |
Return value
Type | Description |
---|---|
String | An element's class, or a list of classes separated by spaces. |
More examples
Example 4
Get the class attribute of the first <div> element (if any):
let value = document.getElementsByTagName("div")[0].className;
Example 5
Get the class attribute of an element with multiple classes:
let value = document.getElementById("myDIV").className;
Example 6
Override the existing class attribute with the new class attribute:
element.className = "newClassName";
Example 7
To add a new class without overriding the existing value, add a space and the new class:
element.className += " class1 class2";
Example 8
If "myDIV" has the "myStyle" class, change the font size:
const elem = document.getElementById("myDIV"); if (elem.className == "mystyle") { elem.style.fontSize = "30px";
Example 9
If you scroll 50 pixels from the top of the page, the "test" class will be added:
window.onscroll = function() {myFunction()}; function myFunction() { if (document.body.scrollTop > 50) { document.getElementById("myP").className = "test"; } document.getElementById("myP").className = "";
browser support
All browsers support element.className
:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
supports | supports | supports | supports | supports | supports |
- Previous Page classList
- Next Page click()
- Go to the Previous Level HTML DOM Elements Object