X
HOME HTML CSS JAVASCRIPT SQL PHP JQUERY ANGULAR BOOTSTRAP XML ASP.NET MORE...
REFERENCES | EXAMPLES | FORUM | ABOUT

HTML DOM className Property

HTMLElement Object Reference Element Object

Example

Set the class for a <div> element with id="myDIV":

document.getElementById("myDIV").className = "mystyle";

Try it yourself »

More "Try it Yourself" examples below.


Definition and Usage

The className property sets or returns the class name of an element (the element's class attribute).


Syntax

Return the className property:

HTMLElementObject.className

Set the className property:

HTMLElementObject.className=class

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


Browser Support

Property
className  Yes Yes Yes Yes Yes


Examples

More Examples

Example

Get the class name of the first <div> element in the document (if any):

var x = document.getElementsByTagName("DIV")[0].className;

The result of x will be:

mystyle

Try it yourself »

Example

Other examples on how to get the class name of an element:

var x = document.getElementsByClassName("mystyle")[0].className;
var y = document.getElementById("myDIV").className;

Try it yourself »

Example

Get the class names of an element with multiple classes:

<div id="myDIV" class="mystyle test example">I am a DIV element</div>

var x = document.getElementById("myDIV").className;

The result of x will be:

mystyle text example

Try it yourself »

Example

Overwriting an existing class name with a new one:

<div id="myDIV" class="mystyle">I am a DIV element</div>

document.getElementById("myDIV").className = "newClassName";

Try it yourself »

Example

To add a class to an element, without overwriting existing values, insert a space and the new class name:

document.getElementById("myDIV").className += " anotherClass";

Try it yourself »

Example

If there's a class of "mystyle" in an element with id="myDIV", change its font-size:

var x = document.getElementById("myDIV");

if (x.className === "mystyle") {
    x.style.fontSize = "30px";
}

Try it yourself »


Related Pages

CSS Tutorial: CSS Selectors

CSS Reference: CSS .class Selector

HTML DOM Reference: HTML DOM getElementsByClassName() Method

HTML DOM Reference: HTML DOM Style Object


HTMLElement Object Reference Element Object

Your suggestion:

Close [X]

Thank You For Helping Us!

Your message has been sent to W3Schools.

Close [X]
Search w3schools.com:

WEB HOSTING

UK Reseller Hosting

WEB BUILDING

Download XML Editor FREE Website BUILDER Free HTML5 Templates

SHARE THIS PAGE

facebook