What is the simplest way to edit CSS variables with jQuery?

395 views Asked by At

I have been able to edit CSS variables with document.documentElement.style.setProperty("--text-color", "#333") however, I haven't been able to reproduce this with jQuery, the .css() prototype only seems to work with known CSS properties.

Here is example CSS for the above CSS variable.

:root {
  --text-color: #888;
}

div {
  color: var(--text-color);
}
1

There are 1 answers

0
BoltClock On BEST ANSWER

As of March 16, 2017, support for custom properties has been shipped in jQuery 3.2.0 and later. There are no plans to backport this functionality to 2.x or earlier, so if you need to use an older version of jQuery for maintenance reasons, you'll need to continue using the built-in style object to access your custom properties.


jQuery does not support custom properties yet. There's a pull request that has yet to be reviewed (but based on recent comments appears to be slated for a near upcoming version). Priority is not that high though, as custom properties are still a fairly new feature and their nature makes both developing a wrapper for browsers that support them natively, re-implementing them in JavaScript for browsers that don't, and testing the feature to make sure everything works without breaking other jQuery features as well as existing sites, quite a task.