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:
xxxxxxxxxx
1
var root = document.querySelector(':root'); // gets root element
2
3
function getVariable(variable) {
4
var style = window.getComputedStyle(root);
5
return style.getPropertyValue(variable);
6
}
7
8
9
// Usage example:
10
11
var value = getVariable('--variable-name');
In this example, we present how to get the existing --primary-color
variable value using getVariable()
function and display it in the console.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
:root {
7
--primary-color: red;
8
}
9
10
</style>
11
</head>
12
<body>
13
<script>
14
15
var root = document.querySelector(':root'); // gets root element
16
17
function getVariable(variable) {
18
var style = window.getComputedStyle(root);
19
return style.getPropertyValue(variable);
20
}
21
22
23
// Usage example:
24
25
var value = getVariable('--primary-color');
26
27
console.log('--primary-color variable value is:' + value);
28
29
</script>
30
</body>
31
</html>