getComputedStyle Reads Custom Property Values

Read resolved styles and custom properties with getComputedStyle; values arrive as strings, so parse numbers yourself before writing scaled values back.

TypescriptConfig Management

Code

typescriptsnippet
19 lines
const card = document.querySelector<HTMLElement>(".price-card");
if (!card) throw new Error(".price-card markup missing");

const styles = getComputedStyle(card);

// 自定义属性读出来一律是字符串:数值要自己解析
const accent = styles.getPropertyValue("--accent").trim();
const gapRaw = styles.getPropertyValue("--card-gap").trim();
const gapPx = parseFloat(gapRaw);

console.log(`--accent: ${accent}`);
console.log(`--card-gap: ${gapRaw}`);
console.log(`gap parsed: ${gapPx}px`);

// 写回新值:element.style.setProperty 是唯一入口
card.style.setProperty("--card-gap", `${gapPx * 2}px`);
const after = getComputedStyle(card).getPropertyValue("--card-gap").trim();
console.log(`after rescale: ${after}`);

How it works

Error is the guard’s signal — thrown at the branch, before any partial work happens.

Module-level bindings hold the data — card, styles, accent, gapRaw — with no function scope in between.

What to watch for

  • Uses document, so it needs a browser context — it will not run as-is in Node without shims.
  • The guard !card short-circuits the flow with an early throw when its condition holds.

Applying it

The demo output is labeled (--accent: $, --card-gap: $, gap parsed: $), so the printed lines read as a per-operation trace of the run.

Statements that matter

if (!card) throw new Error(".price-card markup missing");

Interactive Tools for This Topic

FAQ

What happens on invalid input?
`Error` is raised at the guard (`!card`), so invalid state never reaches the main logic.
Does getComputedStyle Reads Custom Property Values run in plain Node.js?
No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.