HTML DOM Element className property

Definition and usage

className Set or return the class attribute of the element.

See also:

Element classList property

Document getElementsByClassName() method

HTML DOM Style Object

Example

Example 1

Set the class attribute of the element:

element.className = "myStyle";

try it yourself

Example 2

Get the class attribute of "myDIV":

let value = document.getElementById("myDIV").className;

try it yourself

Example 3

Toggle between two class names:

if (element.className == "myStyle") {
  element.className = "newStyle";
}
  element.className = "myStyle";

try it yourself

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;

try it yourself

Example 5

Get the class attribute of an element with multiple classes:




let value = document.getElementById("myDIV").className;

try it yourself

Example 6

Override the existing class attribute with the new class attribute:

element.className = "newClassName";

try it yourself

Example 7

To add a new class without overriding the existing value, add a space and the new class:

element.className += " class1 class2";

try it yourself

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";

try it yourself

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 = "";
  

try it yourself

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

related pages

CSS Tutorial:CSS Syntax

CSS Reference Manual:CSS .class Selector