Languages

CSS - how to change existing CSS variable using JavaScript?

0 points
Asked by:
Jun-L
963

How can I update existing CSS variable using JavaScript?

My code:

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

I want to update --primary-color value to a different one using JavaScript.

Can you help me with that? 

1 answer
0 points
Answered by:
Jun-L
963

This problem is similar to creating CSS variable using JavaScript, you can update existing variable with the same method.

Quick solution:

var root = document.querySelector(':root'); // gets root element

function setVariable(variable, value) {
    root.style.setProperty(variable, value);
}


// Usage example:

setVariable('--primary-color', 'orange');    // updates existing --primary-color to orange
setVariable('--secondary-color', 'yellow');  // creates --secondary-color with yellow value

 

Practical example

In this example, we change the existing --primary-color variable to orange color, then we use it as a background for a div element with .primary class. With the same function, we can also create a new CSS variable (e.g. --secondary-color in the example below).

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

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

    div.primary {
        background-color: var(--primary-color);
    }

    div.secondary {
        background-color: var(--secondary-color);
    }

  </style>
</head>
<body>
  <script>

    var root = document.querySelector(':root'); // gets root element

    function setVariable(variable, value) {
        root.style.setProperty(variable, value);
    }


    // Usage example:

    setVariable('--primary-color', 'orange');    // updates existing --primary-color to orange
    setVariable('--secondary-color', 'yellow');  // sets --secondary-color to yellow

  </script>
  <div class="primary">This div background color (--primary-color) has been changed from red to orange using JavaScript</div>
  <div class="secondary">This div uses --secondary-color that has been set using JavaScript</div>
</body>
</html>

 

See also

  1. CSS - declaring global CSS variables

  2. CSS - get existing CSS variable value

References

  1. :root - CSS: Cascading Style Sheets | MDN
  2. Using CSS custom properties (variables) | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join