How do I get and set CSS custom properties (properties accessed via var(…) in a stylesheet) using JavaScript (plain or jQuery)?
Here is my unsuccessful attempt: clicking the button changes the usual font-weight properties, but not the custom --mycolor properties:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<style>
body {
--mycolor: yellow;
background-color: var(--mycolor);
}
</style>
</head>
<body>
<p>Let's try to make this text bold and the background red.</p>
<button onclick="plain_js()">Plain JS</button>
<button onclick="jQuery_()">jQuery</button>
<script>
function plain_js() {
document.body.style['font-weight'] = 'bold';
document.body.style['--mycolor'] = 'red';
};
function jQuery_() {
$('body').css('font-weight', 'bold');
$('body').css('--mycolor', 'red');
}
</script>
</body>
</html>
Native solution
The standard methods for getting/setting CSS3 variables are
.setProperty()and.getPropertyValue().If your variables are global variables (declared in
:root), you can use the following to get and set their values.// setter document.documentElement.style.setProperty('--myVariable', 'blue'); // getter document.documentElement.style.getPropertyValue('--myVariable');However, if the value of var has been set using
.setProperty(), the getter will only return that value. If set via a CSS declaration,undefinedwill be returned. Check it out in this example:To avoid this unexpected behavior, you must use the
getCompulatedStyle()method before calling.getPropertyValue(). The getter will then look like this:getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');In my opinion, accessing CSS variables should be simpler, faster, intuitive and natural...
My personal approach
I implemented
CSSGlobalVariablesa small ( for easier Access and Operation.Any changes applied to object properties are automatically converted to CSS variables.
Available: https://github.com/colxi/ css-global variables
You can use
document.body.style.setProperty('--name', value);:var bodyStyles = window.getComputedStyle(document.body); var fooBar = bodyStyles.getPropertyValue('--foo-bar'); //get document.body.style.setProperty('--foo-bar', newValue);//set