Sub topic 11
Reading and Writing Tokens from JavaScript
This chapter assumes you can declare custom properties and consume them with var(). It also assumes you know how the cascade and inheritance resolve them, and that you have basic JavaScript. Tokens live in CSS, but scripts sometimes need to read them or change them at runtime. Typical cases are a theme switcher, a user-chosen accent color, or a canvas that must match the page palette.
Reading a token
A custom property is not exposed as a property on element.style. You read it with getComputedStyle() and getPropertyValue().
const root = document.documentElement;
// Read the resolved value of a token
const accent = getComputedStyle(root)
.getPropertyValue('--color-accent')
.trim();
console.log(accent); // "#2563eb"Two details matter here:
getComputedStyle()returns the value after the cascade, so it reflects stylesheets, media queries, and inline overrides.- The returned string often keeps the whitespace from the source. Call
.trim()before comparing or parsing it.
Read from the element whose scope you care about. Tokens inherit, so a value read from a .card can differ from the value read from :root if the card overrides it.
Writing a token
Use style.setProperty() to set an inline override. Inline declarations sit at the top of the normal cascade, so they beat stylesheet rules for that element and its descendants.
// Override a token for the whole document
root.style.setProperty('--color-accent', '#dc2626');
// Remove the override so the stylesheet value applies again
root.style.removeProperty('--color-accent');Every component that uses var(--color-accent) updates at once. No component rule changes. This is the payoff of the token tiers from earlier chapters: scripts only need to touch the token, not the elements.
Scoping a write
You can set a token on any element, not only the root. The override then applies only to that subtree.
const card = document.querySelector('.card');
card.style.setProperty('--card-padding', '2rem');This works well with component tokens. A script adjusts --card-padding on one card without touching the shared --space-4 scale.
Switching themes with a data attribute
For theming, prefer changing an attribute over writing many individual tokens. The stylesheet already defines the dark values under [data-theme="dark"], so the script only flips the switch.
function setTheme(name) {
document.documentElement.dataset.theme = name;
localStorage.setItem('theme', name);
}
const saved = localStorage.getItem('theme');
if (saved) {
setTheme(saved);
}The theme values stay in CSS, where designers can edit them. JavaScript stores the choice and sets the attribute.
Choosing between inline writes and attributes
| Approach | Best for | Drawback |
|---|---|---|
| `setProperty()` on a token | Values the user picks freely, such as a color picker | Values live in JavaScript, not in the token source |
| `data-theme` attribute | A fixed set of themes | You must define each theme in CSS |
Common mistakes
- Forgetting
trim(). A comparison such asvalue === '#2563eb'fails because of a leading space. - Reading before the stylesheet loads. If the script runs early, the token may be empty. Run it after the
loadevent or place the script after the stylesheet link. - Expecting a number.
getPropertyValue()always returns a string. A token set to1remreturns"1rem", not a pixel value. Parse it yourself, or apply it to an element and measure that element. - Leaving stale overrides. An inline value on
:rootwill keep winning over your theme rules. CallremoveProperty()when the override should end.
Exercise
A user picks a color, and your script runs root.style.setProperty('--color-accent', picked). Later the user clicks "Reset". What should the reset code do, and why is setting the value back to the original hex string a weaker choice?
Show answer
Call root.style.removeProperty('--color-accent'). This removes the inline override, so the stylesheet value applies again, including any theme or media query value that currently matches. Writing the original hex string back keeps an inline override in place. It would then ignore later theme changes, such as switching to dark mode, because the inline value beats the stylesheet.