use css variables in javascript code example

Example 1: javascript get css variable

let docStyle = getComputedStyle(document.documentElement);

//get variable
let myVarVal docStyle.getPropertyValue('--my-variable-name');

//set variable
docStyle.setProperty('--my-variable-name', '#fff');

Example 2: css set variable

:root {
  --main-bg-color: coral;
}

#div1 {
  background-color: var(--main-bg-color);
}

#div2 {
  background-color: var(--main-bg-color);
}

Example 3: how to change css variable in javascript

document.documentElement.style.cssText = "--main-background-color: red";

Example 4: js set css variable

document.documentElement.style.setProperty("--main-background-color", "green");

Tags: