Modify CSS variables / custom properties in jQuery
jQuery only supports CSS custom properties in version 3.2.0 and later. There is no support for them in 2.x or earlier, so accessing them with .css()
will not work in those versions. If upgrading jQuery is not an option, you will need to use the built-in style
object to access them.
$(":root").css("--color1", "red");
console.log(".css method on “:root” :", $(":root").css("--color1"));
$(":root")[0].style.setProperty("--color2", "lime");
console.log("[0].style method on “:root” :", $(":root")[0].style.getPropertyValue('--color2'));
#p1 {
background-color: var(--color1);
}
#p2 {
background-color: var(--color2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<p id="p1">p with background --color1</p>
<p id="p2">p with background --color2</p>