Command Palette

Search for a command to run...

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

element.style versus getComputedStyle

style.color was empty because the blue comes from the stylesheet. The width without a unit was silently ignored. Setting backgroundColor to "" removed it from the inline style.

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?

element.style versus getComputedStyle

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

""
rgb(0, 0, 255)
background-color: gold; border-radius: 8px;
rgb(255, 215, 0) 8px
border-radius: 8px;