English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML DOM className Attribute

HTML DOM Element Object

classNameAttribute sets or returns the class attribute value of the specified element as a string.

If the specified element does not have a class attribute or the class attribute is not set, it returns anullString.

Syntax:

Return the className attribute:

element.className

Set the className attribute:

element.className = cName
document.getElementById("x").className = "para";
Test and See‹/›

Browser Compatibility

All browsers fully support the className attribute:

Attribute
classNameIsIsIsIsIs

Attribute Value

ValueDescription
cNameA string variable that represents the current element's class or a space-separated list of classes

Technical Details

Return value:A string that represents the element's class or a space-separated list of classes
DOM Version:DOM Level1

More examples

Return the class name of the first <div> element:

var x = document.getElementsByTagName("div")[0].className;
Test and See‹/›

Overwrite the existing class name with the new name:

<div class="myDiv">This is a DIV element</div>
script>
var x = document.getElementsByTagName("div")[0];
x.className = "anotherClass";
</script>
Test and See‹/›

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

<div class="myDiv">This is a DIV element</div>
script>
var x = document.getElementsByTagName("div")[0];
x.className += " anotherClass";
</script>
Test and See‹/›

Check if the <div> element has the 'shadow' class:

var x = document.getElementsByTagName("div")[0];
if (x.className.indexOf("shadow") != -1) {
   alert("Yes... The DIV has 'shadow' class");
} else {
   alert("False");
}
Test and See‹/›

Related References

CSS Tutorial:CSS Selector

CSS Reference:CSS #idSelector

CSS Reference: CSS .class Selector

JavaScript Reference:String indexOf() Method

HTML DOM Reference:HTML DOM classList Property

HTML DOM Reference:HTML DOM getElementsByClassName() Method

HTML DOM Reference:HTML DOM getElementById() Method

HTML DOM Reference:HTML DOM querySelector() Method

HTML DOM Element Object