Change Variables With JavaScript
Since CSS variables have access to the DOM, JavaScript can both read and change them.
The script below shows one way to display and change --primary-bg-color. Our JavaScript Tutorial is the place to learn more if the language is still new to you.
Example
To read the variable, the script calls getComputedStyle() and then getPropertyValue(). To change the value, the script calls style.setProperty().
Prompt
Create an HTML page that uses CSS variables on the :root element (e.g. --primary-bg-color). Include two buttons: one that uses getComputedStyle and getPropertyValue to alert the current value of --primary-bg-color, and another that uses style.setProperty to change --primary-bg-color to "green". Apply the variable to a container's background color so the change is visible.
Output: complete HTML page
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Change CSS Variables With JavaScript</title>
<style>
:root {
--primary-bg-color: coral;
}
.container {
background-color: var(--primary-bg-color);
padding: 25px;
margin: 20px 0;
}
h1 {
color: white;
}
</style>
</head>
<body>
<h1>Change CSS Variables With JavaScript</h1>
<div class="container">
<p>This container has a background color set by the CSS variable --primary-bg-color.</p>
</div>
<button onclick="myFunction_get()">Get Variable Value</button>
<button onclick="myFunction_set()">Change Variable to Green</button>
<script>
// Get the root element
var r = document.querySelector(':root');
// Function for getting a variable value
function myFunction_get() {
// Get the styles (properties and values) for the root
var rs = getComputedStyle(r);
// Alert the value of the --primary-bg-color variable
alert("The value of --primary-bg-color is: " + rs.getPropertyValue('--primary-bg-color'));
}
// Function for setting a variable value
function myFunction_set() {
// Set the value of variable --primary-bg-color to another value (in this case "green")
r.style.setProperty('--primary-bg-color', 'green');
}
</script>
</body>
</html>