Skip to main content

Change Variables With JavaScript

Since CSS variables have access to the DOM, JavaScript can both read and change them.

The script below shows one way to display and change --primary-bg-color. Our JavaScript Tutorial is the place to learn more if the language is still new to you.

Example

To read the variable, the script calls getComputedStyle() and then getPropertyValue(). To change the value, the script calls style.setProperty().

Prompt
Create an HTML page that uses CSS variables on the :root element (e.g. --primary-bg-color). Include two buttons: one that uses getComputedStyle and getPropertyValue to alert the current value of --primary-bg-color, and another that uses style.setProperty to change --primary-bg-color to "green". Apply the variable to a container's background color so the change is visible.
Output: complete HTML page