In an application where certain elements have custom CSS properties, is there any way to retrieve such a value via JavaScript?
e.g.
<div id="myDiv" style="color:#f00;-my-custom-property:upsidedown;" />
I can access the color attribute via these two methods:
document.getElementById('myDiv').style.getPropertyValue("color")
document.getElementById('myDiv').style.color
But these do not work for custom properties. Is this supported at all?
CSS values not understood by the browser are discarded, which explains why
-my-custom-propertywas unavailable via.style.In the past, you would have had to rely on storing the data with data attributes and dealing with inheritance yourself via JavaScript.
However, “custom properties”, aka “CSS variables”, have since been introduced into the standard and implemented by browsers, with ~92% support globally as of 2019-05-09. At a quick glance, Edge seems to have been the last major browser to implement, with version 16 on October 16, 2017.
Essentially, you need to set a custom property (eg,
--my-custom-property: 'foobar';) on an element, and it can be accessed with something likegetComputedStyle(your_el).getPropertyValue("--my-custom-property")which would return'foobar'(with a leading space). Note the leading space and quotation marks. It will return the value exactly as it was provided.Example:
Here’s some testing using one and two leading hyphens, inheritance, and different methods of retrieving the value: