Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

`className` and `innerHTML`: element classes and content

`className` reflects the element’s `class` attribute. `innerHTML` reads serialized markup or parses markup to replace the element’s contents.

Version: Current web platform; runtime support varies

Syntax

element.className;
htmlElement.className = classString;
element.innerHTML;
element.innerHTML = markup;

Element.className/innerHTML refers to two DOM instance properties, not methods or ECMAScript language features. They are provided by a host with a DOM; a JavaScript engine alone does not supply them.

On an HTML element, className reads the class attribute as a string (empty if absent), and assignment replaces the whole attribute value. To add, remove, or toggle one class without discarding the others, use classList.add(), remove(), or toggle(). On SVG elements, className can be an SVGAnimatedString object rather than a string. For code that handles both kinds of elements, use getAttribute("class") and setAttribute("class", value) to read and write the attribute text. getAttribute() returns null if the attribute is absent.

Reading innerHTML serializes the contents as HTML or XML, excluding the element’s own tags and any shadow roots. It need not reproduce the original source text. Assignment parses a fragment in the element’s context and replaces its children, leaving the element itself in place. For a template, it replaces the template contents instead. Old nodes are detached; references still point to them, and their event listeners do not transfer to new nodes. In an XML document, a fragment that is not well-formed throws a SyntaxError DOMException.

innerHTML does not sanitize markup. Inserted script elements do not execute, but event-handler attributes can still enable XSS. Use textContent to insert plain text into an ordinary element; if you need untrusted markup, sanitize it first. When a supported CSP enforces Trusted Types, assigning a string without a default policy throws TypeError; you can instead pass TrustedHTML produced by a policy that sanitizes the input.

Examples

<!doctype html>
<meta charset="utf-8">
<title>className and innerHTML</title>
<script>
  const card = document.createElement("div");
  const oldChild = document.createElement("span");
  card.append(oldChild);

  card.className = "card draft";
  card.className = "card ready";
  console.log(card.className);
  console.log(oldChild.parentNode === card);

  card.innerHTML = "<strong>Ready</strong>";
  console.log(card.innerHTML);
  console.log(oldChild.parentNode === null);
</script>

Result

card ready
true
<strong>Ready</strong>
true

Save the example as an `.html` file, open it in a browser, and check the console. The first `true` shows that changing classes preserves the old child; the second shows that assigning `innerHTML` detaches it.

Related lessons

  • JavaScript · Lesson 11 · Advanced · Version: 4

Sources