Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Element.className — reading and replacing classes

On an HTML element, use `className` to read or replace the `class` attribute value as a string, not an array of classes. `SVGElement.className` is read-only and returns an `SVGAnimatedString`.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

// For an HTML element:
element.className
element.className = "class1 class2";

Element.className reflects the class attribute. For an HTML element, reading it returns the attribute value as a string; if the attribute is absent, it returns "".

On an HTML element, assigning element.className = "card selected" sets the entire attribute value. Another assignment replaces the previous classes rather than appending one. Separate class names with ASCII whitespace, not commas. A non-breaking space (U+00A0) remains part of a single class name rather than separating two names.

SVGElement.className is read-only and returns an SVGAnimatedString, not a string.

Use className to replace the whole set of classes on an HTML element. For individual-class operations, use element.classList, which exposes a DOMTokenList. This is a DOM API, not an ECMAScript language feature.

Examples

const element = document.createElement("div");
console.log(JSON.stringify(element.className));
element.className = "card selected";
console.log(element.getAttribute("class"));
element.className = "compact";
console.log(element.className);

Result

""
card selected
compact

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources