Remember: custom properties are CSS properties, and we can interact with them as such. For example, we can use the css.supports() API to test whether a browser supports custom properties:
const supportsCustomProps = CSS.supports(‘–primary-text: #000’);
// Logs true to the console in browsers that support custom properties console.log(supportsCustomProps);
You can learn more about the css.supports() API, as well as the @supports CSS rule, in Chapter 10, “Applying CSS Conditionally”.
We can also use the setProperty() method to set a custom property value:
document.body.style.setProperty(‘–bg-home’, ‘whitesmoke’);
Using removeProperty() works similarly. Just pass the custom property name as the argument:
document.body.style.removeProperty(‘–bg-home’);
To use the custom property as a value with JavaScript, use the var() function with the property name as its argument:
document.body.style.backgroundColor = ‘var(–bg-home)’;
Alas, you can’t set custom properties using square-bracket syntax or camelCased properties of the style object. In other words, neither document.body.style.–bg-home nor document.body.style[‘–bg-home’] will work.
Source: Brown Tiffany B (2021), CSS , SitePoint; 3rd edition.