How to change CSS :root color variables in JavaScript

Thank you @pvg for providing the link. I had to stare at it for a little to understand what was going on, but I finally figured it out.

The magical line I was looking for was this:

document.documentElement.style.setProperty('--your-variable', '#YOURCOLOR');

That did exactly what I wanted it to do, thank you very much!


For those who want to modify the actual style sheet the following works:

var sheet = document.styleSheets[0];
sheet.insertRule(":root{--blue:#4444FF}");

More info at here: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule


I came here looking how to toggle the :root color-scheme with JavaScript, which sets the browser to dark mode (including the scroll bars) like this:

:root {
    color-scheme: dark;
}

using the @Daedalus answer above, this is how I implemented my dark mode detection from user preference:

    const userPrefersDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
    const preferredTheme = userPrefersDarkMode ? 'dark' : 'light';
    document.documentElement.style.setProperty("color-scheme", preferredTheme);

or with saved toggle:

    const savedTheme = localStorage.getItem('theme');
    if (savedTheme == 'dark') {
        thisTheme = 'light'
    }
    else {
        thisTheme = 'dark'; // the default when never saved is dark
    }
    document.documentElement.style.setProperty("color-scheme", thisTheme);
    localStorage.setItem('theme', thisTheme);

see also the optional meta tag in the header:

<meta name="color-scheme" content="dark light">

To use the values of custom properties in JavaScript, it is just like standard properties.

// get variable from inline style
element.style.getPropertyValue("--my-variable");

// get variable from wherever
getComputedStyle(element).getPropertyValue("--my-variable");

// set variable on inline style
element.style.setProperty("--my-variable", 4);