Languages
[Edit]
EN

CSS - get existing CSS variable value

3 points
Created by:
Eshaal-Wilkinson
774

In this article, we would like to show you how to get existing CSS variable value using JavaScript.

Quick solution:

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

function getVariable(variable) {
    var style = window.getComputedStyle(root);
    return style.getPropertyValue(variable);
}


// Usage example:

var value = getVariable('--variable-name');

 

Practical example

In this example, we present how to get the existing --primary-color variable value using getVariable() function and display it in the console.

// ONLINE-RUNNER:browser;

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

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

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

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

    function getVariable(variable) {
        var style = window.getComputedStyle(root);
        return style.getPropertyValue(variable);
    }


    // Usage example:

    var value = getVariable('--primary-color');

    console.log('--primary-color variable value is:' + value);

  </script>
</body>
</html>

 

See also

  1. CSS - declaring global CSS variables

  2. CSS - set CSS variable using JavaScript

References

  1. :root - CSS: Cascading Style Sheets | MDN
  2. Using CSS custom properties (variables) | MDN

Alternative titles

  1. CSS - get existing global variable from :root using JavaScript
  2. CSS - get existing CSS variable from script tag using JavaScript
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