How to Get and Set a CSS Variable with JavaScript?

When the size of our application or website grows, the amount of CSS code needed to style it also grows. This often results in a lot of repetition of the same value.

For example, the primary color of your theme might be used in hundreds of different places. So if you want to change it in the future, you have to make changes at each place it is used across the application which can be very time-consuming.

To avoid this problem, CSS has introduced custom properties also called CSS variables or cascading variables. You can define these variables at a global level of your application and then use them anywhere in the entire application.

In this article, I’ll show you how you can define CSS variables, get and set their values dynamically with JavaScript.


Defining CSS Variables

Before we can get and set CSS variables, we need to define them in our stylesheet. CSS variables are defined using the -- prefix and can be used in any property value.

For example:

/* Define a CSS variable */
:root {
    --primary-color: blue;
}

/* Set variable's value to color property */
h1 {
    color: var(--primary-color);
}

Output:

Define a CSS variable

In this example, we’ve defined a CSS variable called --primary-color and set its value to blue color.

We then used this variable in the color property of the main heading(h1) element. Whenever this heading is rendered on the page, its color will be set to the value of the --primary-color variable i.e. blue.


Getting CSS Variables with JavaScript

To get the value of a CSS variable with JavaScript, you can use the getComputedStyle() function. This function returns an object that contains the computed values of all CSS properties applied to an element.

To get the value of the given CSS variable, you can then call the getPropertyValue() method on the returned object from the getComputedStyle() method.

The getPropertyValue() method takes a single parameter which is the name of the CSS variable and returns its value as a string.

Let’s define a CSS variable --primary-color in our stylesheet and apply it to the color property of the h1 element:

/* Define CSS variables */
:root {
    --primary-color: blue;
    --secondary-color: red;
}

/* Set variable's value to color property */
h1 {
    color: var(--primary-color);
}

Now, let’s try to get the value of the variable --primary-color from the h1 element:

// Get the element
const elem = document.querySelector('h1');

// Get element's styles
const elemStyles = getComputedStyle(h1);

// Get CSS variable's value
const primaryColor = elemStyles.getPropertyValue('--primary-color')

console.log(primaryColor);
// 👉 Output: blue


Setting CSS Variables with JavaScript

To set the value of a CSS variable with JavaScript, you can use the setProperty() method on element’s style property.

The setProperty() method takes two parameters, the name of the CSS variable and its value, both as a string and applies to the given element.

Let’s try to apply --primary-color to the color property of the h1 element on the button click:

<h1>This is the main heading.</h1>
<h2>This is a sub heading.</h2>
<button onclick="onBtnClick()">Click Me</button>

Add the CSS:

/* Apply --primary-color to the color property */
h1{
    color: var(--primary-color);
}

Add the JavaScript:

// fires on button click
function onBtnClick(){
    
    // Get the element
    const elem = document.querySelector('h1');

    // Set CSS variable 
    elem.style.setProperty('--primary-color', 'blue');

}

Output:

Set a CSS variable with JavaScript


Updating CSS Variables with JavaScript

One of the benefits of using CSS variables is that you can update their values dynamically with JavaScript.

Let’s try to change the value of --primary-color from blue to red on the button click:

<h1>This is the main heading.</h1>
<h2>This is a sub heading.</h2>
<button onclick="onBtnClick()">Click Me</button>

Add the CSS(old value of --primary-color):

:root{
    --primary-color: blue;
}

/* Apply --primary-color to the color property */
h1{
    color: var(--primary-color);
}

Add the JavaScript:

// fires on button click
function onBtnClick(){
    
    // Get the element
    const elem = document.querySelector('h1');

    // Get styles object
    const styles = getComputedStyle(elem);

    // Old value of --primary-color
    let primaryColor = styles.getPropertyValue('--primary-color');
    console.log(primaryColor); // 👉 outputs "blue"

    // Update the value of --primary-color
    elem.style.setProperty('--primary-color', 'red');

    // Get the updated value
    primaryColor = styles.getPropertyValue('--primary-color');
    console.log(primaryColor); // 👉 outputs "red"
}

Output:

Update a CSS variable with JavaScript

Conclusion

In this article, we learned what are CSS variables and how we can get and set them with JavaScript dynamically.

In summary, to get the value of a CSS variable with JavaScript, we can use the getComputedStyle() and getPropertyValue() methods in combination.

The getComputedStyle() method returns an object that contains all the properties of an element. Now, to get the value of any specific CSS variable from this object, you can use the getPropertyValue() method.

If you want to set the value of a CSS variable dynamically with JavaScript, then you can use the setProperty() method and pass the name and value of the variable to this function as arguments.

Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts