loading

Variables & JavaScript

Change Variables With JavaScript

Because CSS variables are accessible through the DOM, JavaScript can be used to modify them.

This is an illustration of how to write a script that will show and modify the –blue variable from the earlier pages. For the time being, it’s okay if you don’t know anything about JavaScript. See our JavaScript Tutorial for additional information about JavaScript:

Example

				
					<script>
// Get the root element
var r = document.querySelector(':root');

// Create a 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 --blue variable
  alert("The value of --blue is: " + rs.getPropertyValue('--blue'));
}

// Create a function for setting a variable value
function myFunction_set() {
  // Set the value of variable --blue to another value (in this case "lightblue")
  r.style.setProperty('--blue', 'lightblue');
}
</script>
				
			

Browser Support

The numbers in the table specify the first browser version that fully supports the var() function.

Variables &Amp; Javascript -

CSS var() Function

Property Description
var() Inserts the value of a CSS variable
Share this Doc

Variables & JavaScript

Or copy link

Explore Topic