JavaScript’s Element.className property gets and sets the value of the Element’s class attribute.

Value

A string containing the value of the element’s class attribute.

Examples

Here are some examples of using the className property.

Getting the value of the class attribute

Suppose we have the following element:

<span class="orange">What do you think is the most useful JavaScript method?</span>

How can we get the value of the class attribute of the span element with JavaScript?

We can select the element with the querySelector() method and use the className property:

let span = document.querySelector('span');
console.log(span.className);

You should now be able to see the value of the class attribute in the console of your browser.

Setting the value of the class attribute

We can also use the className property to set the value of the class attribute:

let span = document.querySelector('span');
span.className = 'red';

Now the value of the class attribute is “red” instead of “orange.”

Additional notes

You may have wondered why the className property was named “className” and not “class.” That is because of conflicts with the “class” keyword in some languages that are used to manipulate the DOM.

An alternative way to set the value of the class attribute is to use the setAttribute() method. For example, instead of span.className = 'red', we could have written span.setAttribute('class', 'red').

Browser compatibility

Chrome
Edge
Firefox
Internet Explorer
Opera
Safari
Chrome (Android)
Firefox (Android)
Opera (Android)
Safari (iOS)
Samsung Internet
WebView (Android)
className 1 12 1 5 8 1 18 4 10.1 1 1.0 4.4