CSS custom properties (CSS variables) are a modern way to centralise design tokens like colours, spacing, and font sizes. Although jQuery predates their wide adoption, you can read and write CSS variables using a combination of .css() and native DOM APIs, keeping your jQuery code future-friendly.
Reading CSS Variables
jQuery's .css() does not natively support CSS custom property names that start with --. The reliable approach is getComputedStyle(element).getPropertyValue('--var-name') via the DOM, which you can call on the raw element from a jQuery object using index notation: el[0].
Writing CSS Variables
To update a CSS variable use the native element.style.setProperty('--var-name', value). Changing a custom property on :root (the html element) propagates the new value everywhere the variable is used, making it a powerful global theme switch.
- Read:
getComputedStyle($('#el')[0]).getPropertyValue('--primary') - Write:
$('html')[0].style.setProperty('--primary', '#0074d9') - Theme toggle: update one variable on
:rootto retheme the whole page
This pattern is especially useful for dark-mode toggles — simply swap the value of a --bg and --text variable on the root element with a single button click.