Sub topic 11
Reading and writing tokens from JavaScript
This chapter assumes you know how custom properties cascade and inherit, how var() fallbacks work, and how semantic tokens are overridden in a scope. It also assumes you can write basic JavaScript: DOM queries, event listeners, and functions.
Tokens are ordinary CSS, so JavaScript has no special token API. You use the standard style APIs with custom property names. The skill is knowing which API reads the cascaded value, which one writes an override, and where each write lands in the cascade.
The working model
A custom property is a normal CSS property with a name that starts with --. JavaScript touches it in two places.
- Reading goes through the computed style of an element. This is the value after the cascade and inheritance have been applied.
- Writing goes through the element's inline style. An inline declaration takes part in the cascade like any other declaration, and it beats stylesheet rules of normal importance. A stylesheet declaration marked
!importantstill wins over it.
Every consumer of the token, such as var(--color-accent) in a component rule, re-resolves when the inline override changes. No component code needs to know that JavaScript was involved.
Reading a token
Use getComputedStyle and getPropertyValue:
const root = document.documentElement;
const accent = getComputedStyle(root)
.getPropertyValue('--color-accent')
.trim();
console.log(accent); // "#2563eb"Three details cause most reading bugs.
- Use
getPropertyValue, not property access. Names like--color-accentare not exposed as JavaScript properties, sostyle['--color-accent']andstyle.colorAccentdo not work. - Call
.trim(). For an unregistered custom property, the browser may hand back the value with leading whitespace from the declaration. Trimming makes comparisons reliable. - Read from the element that matters. A token can have different values in different scopes. Reading from
document.documentElementreturns the root value, which is not necessarily what a card inside a[data-theme="dark"]section uses.
const panel = document.querySelector('.panel');
const panelText = getComputedStyle(panel).getPropertyValue('--color-text').trim();Because custom properties inherit, the computed style of .panel includes values inherited from its ancestors. That is the value you want when you need to know what a component actually sees.
Computed style versus inline style
element.style.getPropertyValue('--x') reads only the inline declarations on that element. It returns an empty string for a token defined in a stylesheet, which is a common source of "the token is missing" bugs.
| API | What it returns | Typical use |
|---|---|---|
| `getComputedStyle(el).getPropertyValue('--x')` | The resolved value after the cascade and inheritance | Reading the current token value |
| `el.style.getPropertyValue('--x')` | Only the inline value on `el` | Checking whether JavaScript has set an override |
| `el.style.setProperty('--x', v)` | Writes an inline declaration | Overriding a token |
| `el.style.removeProperty('--x')` | Deletes the inline declaration | Reverting to the stylesheet value |
What you get back depends on registration
For an unregistered token, the result is a string close to what the author wrote. If the stylesheet says --space-4: calc(var(--space-base) * 4), you may read back text that is still partly unresolved depending on the browser. Do not parse it as a number.
A token registered with @property has a type, and its computed value is the resolved typed value. A token registered with syntax: "<length>" and written as 1rem reads back as an absolute length such as 16px. If your JavaScript does arithmetic on token values, register the token so the result is predictable.
Writing a token
setProperty takes the name, the value, and an optional priority:
const root = document.documentElement;
// Override the 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');Writing an empty string with setProperty('--color-accent', '') also removes the declaration, but removeProperty states the intent more clearly.
Values are strings. If a token holds a length, include the unit: setProperty('--card-padding', '12px'). If it holds a bare number, such as --accent-hue, pass either a string or a number. JavaScript converts it to text.
Choosing where to write
Where you write decides how far the change travels.
- On
document.documentElement, the override applies to the whole page through inheritance. Use it for user-wide settings such as an accent color. - On a specific element, the override applies to that element and its descendants only. Use it for per-component state, such as a single card.
Writing to the root forces the browser to re-check style for every element that depends on the token. Writing on a narrow element limits the work. For tokens that change many times per second, write as low in the tree as the design allows.
A write on an ancestor does not beat a declaration made on a closer element. If .card declares --card-padding: var(--space-4) itself, then root.style.setProperty('--card-padding', '0') has no visible effect on cards, because the local declaration replaces the inherited value. Write to the element that holds the declaration, or change the token that the local declaration reads from (here, --space-4).
A small token helper
Wrapping the calls in a helper gives you one place to validate names and one place to change behavior later.
const root = document.documentElement;
function assertTokenName(name) {
if (!name.startsWith('--')) {
throw new TypeError(`Token names must start with "--": ${name}`);
}
}
export function getToken(name, el = root) {
assertTokenName(name);
return getComputedStyle(el).getPropertyValue(name).trim();
}
export function setToken(name, value, el = root) {
assertTokenName(name);
el.style.setProperty(name, String(value));
}
export function resetToken(name, el = root) {
assertTokenName(name);
el.style.removeProperty(name);
}The assertTokenName check catches a typo such as setToken('color-accent', ...). Without it, setProperty ignores the call silently, because color-accent is not a valid property name.
Switching themes from JavaScript
For themes, prefer toggling an attribute over writing many tokens. The theme definitions stay in CSS, where designers can read them, and JavaScript only chooses which one applies. This pairs with the [data-theme="dark"] rule from the theming chapter.
const root = document.documentElement;
const STORAGE_KEY = 'theme';
function applyTheme(theme) {
if (theme === 'light' || theme === 'dark') {
root.dataset.theme = theme;
localStorage.setItem(STORAGE_KEY, theme);
} else {
delete root.dataset.theme;
localStorage.removeItem(STORAGE_KEY);
}
}
// Restore the saved choice on load
applyTheme(localStorage.getItem(STORAGE_KEY));
document.querySelector('#theme-toggle').addEventListener('click', () => {
const current = root.dataset.theme;
applyTheme(current === 'dark' ? 'light' : 'dark');
});When no data-theme attribute exists, the prefers-color-scheme media query decides. When the attribute is set, it takes over. Apply the saved theme in a small script in the <head> so the page does not flash the wrong colors before the script runs.
Feeding runtime values into CSS
JavaScript is good at values CSS cannot know, such as pointer position or scroll progress. Write them as tokens and let CSS decide how to use them.
<div class="spotlight">Move the pointer over me</div>.spotlight {
--mx: 50%;
--my: 50%;
padding: 4rem;
background: radial-gradient(
circle at var(--mx) var(--my),
var(--color-accent, #2563eb),
transparent 60%
);
}const spotlight = document.querySelector('.spotlight');
spotlight.addEventListener('pointermove', (event) => {
const rect = spotlight.getBoundingClientRect();
spotlight.style.setProperty('--mx', `${event.clientX - rect.left}px`);
spotlight.style.setProperty('--my', `${event.clientY - rect.top}px`);
});The tokens are written on .spotlight rather than the root, so only that element and its children are re-styled on each event. The CSS keeps its defaults (50%) and works even if the script never runs.
Re-reading tokens when something changes
Some consumers cannot use var(). A <canvas> drawing or a charting library takes color strings, not CSS. Read the tokens when you draw, and read them again when the theme changes.
const canvas = document.querySelector('#chart');
const ctx = canvas.getContext('2d');
function draw() {
const styles = getComputedStyle(canvas);
const accent = styles.getPropertyValue('--color-accent').trim();
const surface = styles.getPropertyValue('--color-surface').trim();
ctx.fillStyle = surface;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = accent;
ctx.fillRect(20, 20, 120, 60);
}
draw();
const media = window.matchMedia('(prefers-color-scheme: dark)');
media.addEventListener('change', draw);
new MutationObserver(draw).observe(document.documentElement, {
attributes: true,
attributeFilter: ['data-theme'],
});Reading from the canvas element means a themed ancestor is respected. The two listeners cover both ways the theme can change: the operating system setting and the data-theme attribute.
Registering a token from JavaScript
@property has a JavaScript equivalent, CSS.registerProperty. It is useful when a library needs to register its own tokens without shipping CSS.
CSS.registerProperty({
name: '--accent-hue',
syntax: '<number>',
inherits: false,
initialValue: '220',
});A property can be registered only once. Registering the same name again throws an InvalidModificationError, and a name already registered in CSS counts. Wrap the call in try/catch if the code might run twice.
Common errors
- Reading an empty string. The token is not defined on that element, the name is misspelled, or you used
el.style.getPropertyValueon a stylesheet token. Names are case-sensitive:--Color-Accentand--color-accentare different tokens. - Writing a token that has no effect. A closer element redeclares the token, or a stylesheet
!importantdeclaration wins. Inspect the element's computed value in the browser's developer tools. - Writing a bad value. An unregistered token accepts any text, so
setProperty('--space-4', 'banana')succeeds. Every property that usesvar(--space-4)then becomes invalid at computed-value time and falls back to its inherited or initial value. A registered token rejects a value that does not match its syntax, and the old value stays. - Reading too early. Read tokens after the stylesheet has loaded, for example inside a
DOMContentLoadedorloadhandler, or after the element is in the DOM. Before that, the result can be empty. - Leaving stale inline overrides. Inline overrides persist until removed. After a "reset" feature, call
removePropertyfor each token you set, or you will see values that no stylesheet change can fix.
Summary
Read tokens with getComputedStyle(el).getPropertyValue(name).trim(), and write overrides with el.style.setProperty(name, value) and removeProperty(name). Reads reflect the cascade at that element, and writes become inline declarations that follow cascade rules. Write as low in the tree as the design allows, switch themes with an attribute, and re-read tokens when the theme changes.
Exercise
A page defines --color-accent: #2563eb; in a stylesheet on :root. Your script runs document.documentElement.style.getPropertyValue('--color-accent') and gets an empty string. Why, and how do you get the real value?
Show answer
element.style holds only inline declarations, and the token was set in a stylesheet. Use getComputedStyle(document.documentElement).getPropertyValue('--color-accent').trim() to read the resolved value.
Exercise
You call document.documentElement.style.setProperty('--card-padding', '0'), but .card elements still show their padding. The CSS has .card { --card-padding: var(--space-4); padding: var(--card-padding); }. Give two ways to fix it.
Show answer
The .card rule declares --card-padding itself, so the inherited root override is replaced. Either write the override on each card element (card.style.setProperty('--card-padding', '0')), or change the token the card reads from, --space-4, on the root.
Exercise
What happens if you run setProperty('--space-4', 'banana') on an unregistered token, and what changes if --space-4 is registered with syntax: "<length>"?
Show answer
For an unregistered token the value is accepted, and every declaration using var(--space-4) becomes invalid at computed-value time. For a registered <length> token, the invalid value is rejected and the previous value stays in effect.