Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 8.5 — Changing Styles from JavaScript
JavaScript · Example 2 of 3

Switching a state with a class

JavaScript only switched the class; the CSS decided what "selected" looks like. The transition is turned off here only so the console can read the final colour at once; normally you'd keep it.

element.style reads and writes an element's inline styles, getComputedStyle reads the final styles the browser actually applied, CSS variables can be set from JavaScript with setProperty, and toggling classes is usually the cleanest way to change looks.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write setProgress(percent) that sets the width of #bar to that percentage and its background to crimson below 30, otherwise seagreen. Log the inline style after setProgress(20).

02

Write toggleDark() that toggles the class dark on <html> and returns the computed background colour of <body>, with CSS .dark body { background: rgb(17, 17, 17); }.

Explain it without notes

01

What is the difference between element.style and getComputedStyle(element)?

02

Why is toggling a class usually better than setting inline styles?

03

How do you change a CSS custom property from JavaScript, and why is that useful for theming?

04

How should you hide and show an element from JavaScript?

Switching a state with a class

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

Before: rgb(204, 204, 204)
Selected: rgb(65, 105, 225) rgb(238, 242, 255)
After: rgb(204, 204, 204)