JavaScript lesson · 22 min

JavaScript Changing Text and Classes

Update textContent and classList to change what a page says and how it looks.

Code runs locally in your browser

What you will practice

  • Change element text with textContent.
  • Add and check CSS classes with classList.
  • Connect state changes to visible UI changes.

What this means

`textContent` changes the text inside an element without treating the text as HTML.

`classList` lets JavaScript add, remove, toggle, and check CSS classes.

Many interfaces work by changing text and classes: loading states, success messages, selected tabs, hidden panels, and error labels.

If this is your first time seeing this

Changing text changes what the user reads.

Changing classes changes which CSS styles apply to an element.

Mini glossary

textContent
A safe way to set plain text inside an element.
classList
An API for adding, removing, toggling, and checking classes.
State
The current condition of the interface, such as ready, loading, or error.

Example from everyday life

Changing text and classes is like changing a sign on a door. The sign can say `Draft` or `Published`, and a colored sticker can show whether the room is ready.

How it works step by step

  1. The code creates a paragraph with the text `Draft`.
  2. `status.textContent = "Published"` changes the visible text.
  3. `status.classList.add("is-ready")` adds a class that CSS could style.
  4. `classList.contains` checks whether that class is present.

Where you will use this

  • A save button changes from `Saving...` to `Saved`.
  • A form field gets an `error` class when validation fails.
  • A tab component adds an `active` class to the selected tab.

Before you run the code

Use `textContent` for plain text. It is safer than `innerHTML` when you are showing user input.

Classes are usually how JavaScript talks to CSS. JavaScript decides the state; CSS decides the visual style.

Common beginner mistakes

  • Using `innerHTML` when only plain text is needed.
  • Forgetting that CSS must exist for a class to visibly change the page.
  • Changing a variable but forgetting to update the DOM.

Run in browser

Try the example

Console output
Run the code to see console output here.
Exercise checks0 of 2 checks passed.
WaitingChanges the visible text
WaitingAdds a CSS class

Code runs locally in an isolated sandboxed browser frame with a timeout. It is not sent to Lumio analytics or executed on the server.

Try changing this next

  • Change `Published` to `Saved`.
  • Add another class with `classList.add`.
  • Use `classList.remove("is-ready")` and check the result.