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:

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

or

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

or

document.documentElement.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() {
    document.documentElement.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);
}

This will only work in browsers supporting CSS variables obviously.

Answer from Brett DeWoody on Stack Overflow
🌐
W3Schools
w3schools.com › css › css3_variables_javascript.asp
CSS Change Variables With JavaScript
CSS variables have access to the DOM, which means that you can change them with JavaScript.
Discussions

How Do I Reference CSS Variables In My HTML Document?
HTML has no way of interacting with the stylesheet, it can't read CSS variables. You could do it using JavaScript with getComputedStyle and getPropertyValue . More on reddit.com
🌐 r/learnprogramming
3
1
December 5, 2022
Is it safe to use css variables ?
Caniuse.com is your best friend for any doubt like this. More on reddit.com
🌐 r/css
21
12
August 10, 2022
Passing CSS variables from JavaScript to scoped styles
I would create a computed that maps your "type" to your color css var. ie: enum colors { success: '--color-success', ... } const color = computed(() => \var(${colors[type]})`)` (this should return something like "var(--color-success)" so CSS can use) Then in the css, use v-bind: color: v-bind(color) More on reddit.com
🌐 r/vuejs
6
2
January 15, 2024
CSS वेरिएबल CoreUI for React.js में जैसा चाहिए वैसा काम नहीं कर रहा ...
🌐 r/react
🌐
OpenReplay
blog.openreplay.com › setting-and-updating-css-variables-with-javascript
Setting and Updating CSS Variables with JavaScript
March 20, 2024 - In this code, we set the paragraph color to blue in a stylesheet and later changed it to pink with JavaScript. Updating CSS variables with JavaScript could be helpful when you want to give users control over the CSS styling.
🌐
CSS-Tricks
css-tricks.com › updating-a-css-variable-with-javascript
Updating a CSS Variable with JavaScript | CSS-Tricks
September 12, 2018 - 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.
🌐
Vue School
vueschool.io › home › tutorials › how to update :root css variable with javascript
How to Update :root CSS Variable with Javascript - Vue School Articles
December 21, 2024 - In this example, clicking the button triggers the changeColor method, which updates the --main-color CSS variable. ... The background color of the page will change accordingly. To take things further, you can use Vue.js’ watch API to reactively update CSS variables based on data changes.
🌐
Observable
observablehq.com › @triptych › how-to-change-the-value-of-css-variables-with-javascript-unt
How to Change the Value of CSS Variables with JavaScript / Andrew Wooldridge | Observable
July 29, 2022 - An Observable notebook implementing the tips from https://stackdiary.com/snippet/change-css-variable-value-javascript/ Let's add to this tutorial:
🌐
TutorialsPoint
tutorialspoint.com › get-and-set-css-variables-with-javascript
Get and Set CSS Variables with JavaScript
October 28, 2024 - <!DOCTYPE html> <html lang="en"> <head> <style> :root { --custom-bg-color: rgb(138, 21, 21); } .container { display: flex; justify-content: center; height: 200px; align-items: center; background-color: var(--custom-bg-color); } button { padding: 15px; font-size: 20px; cursor: pointer; } </style> </head> <body> <div class="container"> <button onclick="toggle()"> Change Theme </button> </div> <script> function toggle() { let root = document.documentElement; let currColor = getComputedStyle(root) .getPropertyValue('--custom-bg-color'); if (currColor === 'rgb(138, 21, 21)') { root.style.setProperty('--custom-bg-color', 'black'); } else { root.style.setProperty('--custom-bg-color', 'rgb(138, 21, 21)'); } } </script> </body> </html> In this article to get and set CSS variables with JavaScript, we have used getComputedStyle(), getPropertyValue() and setProperty() method.
Find elsewhere
🌐
David Walsh
davidwalsh.name › css-variables-javascript
How to Get and Set CSS Variable Values with JavaScript
October 8, 2018 - The computed variable value comes back as a string. To set the value of a CSS variable using JavaScript, you use setProperty on documentElement's style property:
🌐
JavaScript in Plain English
javascript.plainenglish.io › how-to-use-javascript-to-update-css-variables-135d17b5577c
How to Use JavaScript to Update CSS Variables | by Danielle Dias | JavaScript in Plain English
May 29, 2023 - In the above code, we select an element with the class .element and use the setProperty method to change the value of the --primary-color variable to #ff0000, which represents the color red. As a result, the color of the element will be updated accordingly. One of the most powerful use cases for updating CSS variables with JavaScript is responding to user interactions.
🌐
YouTube
youtube.com › watch
Changing CSS variables with JavaScript (CSS custom ...
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › CSS › Guides › Cascading_variables › Using_custom_properties
Using CSS custom properties (variables) - MDN Web Docs
Custom properties (sometimes referred to as CSS variables or cascading variables) are entities defined by CSS authors that represent specific values to be reused throughout a document. They are set using the @property at-rule or by custom property syntax (e.g., --primary-color: blue;). Custom properties are accessed using the CSS var() function (e.g., color: var(--primary-color);).
🌐
Zell Liew
zellwk.com › home › blog › the easiest way to get and set css variables in javascript
The easiest way to get and set CSS Variables in JavaScript | Zell Liew
December 5, 2023 - If you wrote the variable in another selector, you need to use document.querySelector to find the element first. ... property is the CSS variable you want to set.
🌐
Designcise
designcise.com › web › tutorial › how-to-update-a-css-variable-using-javascript
How to Update a CSS Variable Using JavaScript? - Designcise
November 1, 2020 - Using the style.setProperty() method we can override/update global or local scoped CSS variables. It has the following syntax: style.setProperty(propertyName, value, priority); Where propertyName in our case would be the CSS variable we wish ...
🌐
Linux Hint
linuxhint.com › change-css-variables-javascript
How to change CSS variables through javascript?
Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
🌐
Huntertrammell
huntertrammell.dev › blog › using-css-variables-to-create-interactive-styling
Using CSS Variables with JavaScript to create interactive styling
June 17, 2022 - You can create and use CSS variables under any selector, but by using the :root selector you can define variable properties that can be inherited by all selectors.
🌐
Byby
byby.dev › css-vars-with-js
How to get and set CSS variables with JavaScript
July 20, 2023 - CSS variables are custom properties that can be declared and used in your stylesheets. They can also be accessed by JavaScript using getPropertyValue() and setProperty().
🌐
Ryan Dejaegher
ryandejaegher.com › update-css-variables-javascript
Update CSS Variables on CSS Selectors With JavaScript | Ryan Dejaegher
July 30, 2021 - Similar to setting styles on the :root, we can grab any CSS selector with JavaScript and use the setProperty() method to update the variable. var theme = document.querySelector('.cool-theme'); theme.style.setProperty('--primary-brand', 'yellow'); ...
🌐
CodePen
codepen.io › wesbos › pen › adQjoY
Update CSS Variables with JS
... Visit your global Editor Settings. ... <h2>Update CSS Variables with <span class='hl'>JS</span></h2> <div class="controls"> <label>Spacing:</label> <input type="range" id="spacing" min="10" max="200" valu
🌐
Matt Ferderer
mattferderer.com › how-to-get-a-css-variable-with-java-script-and-set-one-too
How to Get a CSS Variable with JavaScript and Set One Too | Matt Ferderer
October 29, 2020 - While working on a redesign, I needed a way for JavaScript to get the value of a CSS variable to determine the state of a page. Lucky for us, there is a browser compatible and easy method.