How do I edit a CSS variable using JS?

javascript change css variable root
change css variable with javascript
css variables browser support
using javascript constants in css
how to change scss variable value dynamically
use css calc in javascript
use a custom css variable
global css variables

I have these CSS variables to control the colors of my project so I can do theming.

html {
    --main-background-image: url(../images/starsBackground.jpg);
    --main-text-color: #4CAF50;
    --main-background-color: rgba(0,0,0,.25);
    --beta-background-color: rgba(0,0,0,.85);
}

However no matter how I try to change the attribute(the two commented lines tried separately), the closest I get is returning not a valid attribute.

function loadTheme() {
    var htmlTag = document.getElementsByTagName("html");
    var yourSelect = document.getElementById( "themeSelect" );
    var selectedTheme = ( yourSelect.options[ yourSelect.selectedIndex ].value );
    // htmlTag[0].setAttribute('--main-text-color', '#FFCF40');
    // $("html").css("--main-text-color","#FFCF40");
}

Turns out changing CSS variables is possible using the el.style.cssText property, or el.style.setProperty or el.setAttribute methods. In your code snippets el.setAttribute is incorrectly used, which is causing the error you encountered. Here's the correct way:

var html = document.getElementsByTagName('html')[0];
html.style.cssText = "--main-background-color: red";

or

var html = document.getElementsByTagName('html')[0];
html.style.setProperty("--main-background-color", "green");

or

var html = document.getElementsByTagName('html')[0];
html.setAttribute("style", "--main-background-color: green");

Demo

The following demo defines a background color using a CSS variable, then changes it using the JS snippet 2 seconds after loading.

window.onload = function() {
  setTimeout(function() {
    var html = document.getElementsByTagName('html')[0];
    html.style.cssText = "--main-background-color: red";
  }, 2000);
};
html {
    --main-background-image: url(../images/starsBackground.jpg);
    --main-text-color: #4CAF50;
    --main-background-color: rgba(0,0,0,.25);
    --beta-background-color: rgba(0,0,0,.85);
}

body {
  background-color: var(--main-background-color);
}

Updating a CSS Variable with JavaScript, Here's a CSS variable (formally called a "CSS custom property"): :root { --mouse-​x: 0px; --mouse-y: 0px; } Perhaps you use them to set a  Setting a CSS Variable's Value. To set the value of a CSS variable using JavaScript, you use setProperty on documentElement's style property: document.documentElement.style .setProperty('--my-variable-name', 'pink'); You'll immediately see the new value applied everywhere the variable is used.

If you are using :root:

:root {
    --somevar: black;
}

It will be documentElement.

document.documentElement.style.setProperty('--somevar', 'green');

How do I edit a CSS variable using JS?, Turns out changing CSS variables is possible using the el.style.cssText property, or el.style.setProperty or el.setAttribute methods. In your code  One is the CSS readability: If you want to pin an element to the position of your cursor, left: var(--mouse-x) just makes total sense to me. And if there are more than one element reacting to the movement of your mouse, you don’t have to update them one by one in your JS – you simply update the CSS variable once.

You can simply use the standard way of setting arbitrary CSS properties: setProperty

document.body.style.setProperty('--background-color', 'blue');
body {
  --background-color: red;
  background-color: var(--background-color);
}

Setting CSS Styles using JavaScript, property directly on the element. The other way is by adding or removing class values from an element which may result in certain style rules getting applied or ignored. As of 2016, CSS Variables are fully usable in Chrome and Firefox, and IE has declared their intention to implement it as well. Like many of the new JavaScript and CSS features, it can be a little hard to visualize what you might need or use a CSS variable for.

The native solution

The standard methods to get/set CSS3 variables are .setProperty() and .getPropertyValue().

If your Variables are Globals (declared in :root), you can use the following, for getting and setting their values.

// setter
document.documentElement.style.setProperty('--myVariable', 'blue');
// getter
document.documentElement.style.getPropertyValue('--myVariable');

However the getter will only return the value of a var, if has been set, using .setProperty(). If has been set through CSS declaration, will return undefined. Check it in this example:

let c = document.documentElement.style.getPropertyValue('--myVariable');
alert('The value of --myVariable is : ' + (c?c:'undefined'));
:root{ --myVariable : red; }
div{ background-color: var(--myVariable); }
  <div>Red background set by --myVariable</div>

Learn CSS Variables in 5 minutes, it on the :root pseudo-class. It matches the root element in your document tree (usually the <html> tag). When the CSS property is just one word, such as margin or border, you can use the same CSS name to change the style in JavaScript. If the CSS property has dashes ( ‐ ), the CSS property name gets converted to camelCase. So, background‐color gets changed to backgroundColor.

You could add something like below (without using class variables)

function loadTheme() {
  var htmlTag = document.getElementById("myDiv");
  var yourSelect = document.getElementById("themeSelect");
  var selectedTheme = (yourSelect.options[yourSelect.selectedIndex].value);
  console.log("selected theme: " + selectedTheme);

  // reset class names
  htmlTag.className = '';
  // add selected theme
  htmlTag.className = 'theme' + selectedTheme;
}
.theme1 {
  color: blue;
}
.theme2 {
  color: red;
}
<div id="myDiv">
  test
</div>
<select id="themeSelect" onChange="loadTheme()">
  <option value="1">Theme 1</option>
  <option value="2">Theme 2</option>
</select>

Everything you need to know about CSS Variables, In this demo we are going to build a simple form that will use JS to dynamically update CSS variables(in our case change color and margin of a  Using Events. The HTML DOM allows you to execute code when an event occurs. Events are generated by the browser when "things happen" to HTML elements: An element is clicked on; The page has loaded; Input fields are changed; You will learn more about events in the next chapter of this tutorial.

How to access Session variables and set them in javascript , Custom properties (sometimes referred to as CSS variables or They are set using custom property notation (e.g., --main-color: black;) and are requiring global search and replace if that color needs to change. To use the values of custom properties in JavaScript, it is just like standard properties. Ignoring inline styles, the other approach that we can use to introduce elements to the goodness that is CSS styling involves JavaScript. We can use JavaScript to directly set a style on an element, and we can also use JavaScript to add or remove class values on elements which will alter which style rules get applied.

Accessing and modifying CSS variables with Javascript, To anyone familiar with SASS or a similar language which compiles to CSS, the advantage of this is obvious, you can easily change colors, sizes, etc. in a single​  The var () Function. Variables in CSS should be declared within a CSS selector that defines its scope. For a global scope you can use either the :root or the body selector. The variable name must begin with two dashes (--) and is case sensitive! The syntax of the var () function is as follows: var ( custom-name, value) Value. Description.

Using CSS custom properties (variables), In this video we are going to set a simple example on how to change CSS variable with Duration: 12:59 Posted: Apr 21, 2019 Custom properties (sometimes referred to as CSS variables or cascading variables) are entities defined by CSS authors that contain specific values to be reused throughout a document. They are set using custom property notation (e.g., --main-color: black;) and are accessed using the var () function (e.g., color: var (--main-color); ).

Comments
  • I don't recall --main-text-color being a valid CSS attribute. Is that using a a pre-processor?
  • No it is a css variable. I found out about them in this article
  • broken-links.com/2014/08/28/…
  • Yes, those CSS variables use a 'native' pre-processor (basically, they eventually get converted into the real property/attribute beforehand). BTW, this feature is not widely supported by all browsers (only FF, from the article. I dunno about other browsers) - in any case, your syntax is incorrect if you want to manipulate them in JS. You need to manipulate properties (not attributes, it seems) - so try htmlTag[0].styles.setProperty('--main-text-color', '#FFCF40');
  • I copied your answer in and now the error is that it can not set property of undefined. Could I bother you for a fiddle example?
  • This will overwrite the existing inline styles.
  • yes you need to modify the prop like this: document.querySelector("html").style.setProperty('width', fixed.width + 'px') however I can't get it to work
  • has someone got SuperUberDuper comment working?
  • for some reason I can't get this to work when the var is used in a transition like so: left: calc(10% - (var(--width) / 2));
  • Downvoted because it doesn't answer the question at all.
  • @Ced wait! are you saying that my answer does not address the OP's need to do theming? - I am not sure I'd agree with you. Just because I answer in a widely-supported ways (instead of using a limited-browser-support approach) - please read: How To Answer (stackoverflow.com/help/how-to-answer) -> Answers can be "don't do this" but "try this instead".... shrugs
  • This is more of a comment than an answer
  • I didn't think about that. I'll give that a shot and get back to you