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.
Code
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
!cardshort-circuits the flow with an earlythrowwhen 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
Properties File ParserParse Java .properties files with comments, continuations, separators, and escapes, then emit clean JSON.Aspect Ratio CalculatorSimplify a width-to-height ratio, show its decimal value, and derive a matching height for a new width.Border Radius PreviewPreview four-corner border-radius values on a live box and copy the generated shorthand border-radius CSS declaration.Box Shadow GeneratorBuild CSS box-shadow values with offset, blur, spread, color, opacity, and inset controls, with a live preview of the result.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.