Monday, November 28, 2022
HomeCSSjavascript - How do I edit a CSS variable utilizing JS?

javascript – How do I edit a CSS variable utilizing JS?

The native answer

The commonplace strategies to get/set CSS3 variables are .setProperty() and .getPropertyValue().

In case your Variables are Globals (declared in :root), you need to use the next, for getting and setting their values.

// setter
doc.documentElement.type.setProperty('--myVariable', 'blue');
// getter

Nonetheless the getter will solely return the worth of a var, if has been set, utilizing .setProperty().
If has been set via CSS declaration, will return undefined. Test it on this instance:

let c = doc.documentElement.type.getPropertyValue('--myVariable');
alert('The worth of --myVariable is : ' + (c?c:'undefined'));
:root{ --myVariable : pink; }
div{ background-color: var(--myVariable); }
  <div>Purple background set by --myVariable</div>

To keep away from that surprising habits it’s important to make use of the getComputedStyle()methodology , earlier than calling .getPropertyValue().
The getter will then , look lik this :


For my part, accessing CSS variables needs to be extra easy, quick, intuitive and pure…

My private method

I’ve applied CSSGlobalVariables a tiny (<3kb) javascript module wich robotically detects and packs into an Object, all of the lively CSS world variables in a doc, for simpler acces & manipulation.

import {CSSGlobalVariables} from './css-global-variables.js';
let cssVar = new CSSGlobalVariables();
// set the CSS world --myColor worth to "inexperienced"
cssVar.myColor = "inexperienced";

Any change utilized to the Object properties, is translated robotically to the CSS variables, and viceversa.

Obtainable in :



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments