HTML DOM Element ClassName Property - W3Schools

HTML DOM Element className ❮ Previous ❮ Element Object Reference Next

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.

Description

The className property sets or returns an element's class attribute.

See Also:

The Element classList Property

The Document getElementsByClassName() Method

The HTML DOM Style Object

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
StringThe 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 »

Related Pages

CSS Tutorial: CSS Syntax

CSS Reference: CSS .class Selector

Browser Support

element.className is supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes
Previous ❮ Element Object Reference Next +1 Sign in to track progress

Tag » Add Classname To Element Javascript