How to Change the Value of CSS Variables with JavaScript

In this tutorial, we will learn how to change the value of CSS variables with JavaScript using the document.querySelector method. The document.querySelector method allows us to select an element in the DOM and access its styles. We can use this method to change the value of a CSS variable and see the changes reflected on the page where the click event happens.

How to Change the Value of CSS Variables with JavaScript

CSS Variables are pretty much the gold standard in building designs from scratch, which has been further amplified by having variables integrated as part of popular CSS libraries and frameworks.

So, the following snippet is really about using document.querySelector – selecting the specified style, querying the variable, and then changing the value based on addEventListener.

CSSHTMLJavaScript
/* creating a style declaration, and defining a custom variable */
:root {
    --demo-color-change: #0b32e7;
}
/* using the custom variable to style our  */
.css-v-demo p {
    color: var(--demo-color-change);
}
.css-v-demo .btn-css-v {
    text-align: center;
    padding: 8px;
    color: #fff;
    width: 100px;
}
<div class="main css-v-demo">
    <h2>This is the header for our demo.</h2>
    <p>This is some text.</p>
    <div>
        <p class="p">And some more text.</p>
    </div>
</div>
<div class="btn btn-css-v">Click me to change text color!</div>

<!-- We'll use the button to trigger the color change. -->
// selecting the :root theme
const root_theme = document.querySelector(':root');

// seleting the button which will trigger the event
const root_btn = document.querySelector('.btn-css-v');

// the event listener to change the text color upon 'click'
root_btn.addEventListener('click', () => {
    // changing the color from #0b32e7 to #f44336
    root_theme.style.setProperty('--demo-color-change', '#f44336'); 
});

The last piece of the puzzle is the style.setProperty declaration. This lets us directly query the variable within which the variable data is stored. Worth noting that this method works for any CSS property/element, so not limited to CSS Variables alone.


This is the header for our demo.

This is some text.

And some more text.

Click me to change text color!

This method can then be implemented in a large number of use cases. For example, you can create a custom widget to let users change the font-size of your body content. Additionally, this method can be used to apply various filters to images and let users preview different outcomes.