EN
CSS - get existing CSS variable value
3
points
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>