Assume I have the following CSS:
div {
-my-foo: 42;
}
Can I later in JavaScript somehow know what the value of the -my-foo
CSS property is for a given div
?
CSS variables have access to the DOM, which means that you can change them with JavaScript.
They are set using custom property notation (e.g., --main-color: black; ) and are accessed using the var() function (e.g., color: var(--main-color); ).
CSS custom properties are also referred to as CSS variables or cascading variables. These entities contain specific values that will be reused in the entire document & can be accessed using the var() function (e.g., color:(–primary-color);).
The @property “at-rule” in CSS allows you to declare the type of a custom property, as well its as initial value and whether it inherits or not.
I don't think you can access invalid property names, at least it doesn't work in Chrome or Firefox for me. The CSSStyleDeclaration simply skips the invalid property. For the given CSS:
div {
width: 100px;
-my-foo: 25px;
}
style:CSSStyleDeclaration
object contains only the following keys:
0: width
cssText: "width: 100px"
length: 1
However, interestingly this is what the DOM-Level-2 Style spec says:
While an implementation may not recognize all CSS properties within a CSS declaration block, it is expected to provide access to all specified properties in the style sheet through the CSSStyleDeclaration interface.
implying that the CSSStyleDeclaration object ought to have listed the -my-foo
property in the above example. Maybe there is some browser out there which supports it.
The code I used for testing is at http://jsfiddle.net/q2nRJ/1/.
Note: You can always DIY by parsing the raw text. For example:
document.getElementsByTagName("style")[0].innerText
but that seems like a lot of work to me, and not knowing your reasons for doing this, I can't say if a better alternate for your problem exists.
As pointed out by Anurag, this was something proposed in DOM Level 2 and later deprecated. Internet Explorer was the only browser that implemented it and they stopped supporting it in Edge. IE expects that the property doesn't start with a dash so my-foo: 42;
should work.
Newer browsers support CSS variables. These start with a double dash: --my-foo: 42;
(they can be reused elsewhere like this font-size: var(--my-foo);
)
div {
--my-foo: 42;
my-foo: 42;
}
// Chrome 49, Firefox 31, Safari 9.1 (future Edge):
const cssVariable = bodyStyles.getPropertyValue('--my-foo')
// IE:
const cssCustomProperty = bodyStyles['my-foo']
Currently Microsoft Edge is the only browser with no support for either of these methods, but as of writing CSS variables in Edge are "under active development".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With