EN
CSS - how to change existing CSS variable using JavaScript?
1
answers
0
points
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
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
References
0 comments
Add comment