In jQuery, I can get a CSS property value for a selector using the css method and passing a property name, for example:
$('#myElement').css('backgroundImage');
My question is, how can I get a css property value from a class that is not yet applied to any element? Similar to $('.myClass').css('backgroundImage');
where the selector returns zero elements but there is a CSS declaration for that class.
You can create a temporary element without adding it to the DOM, and inspect the relevant property. CSS will apply, even if the element is not added to the DOM. E.g.
CSS
p { color: red; }
JS
var p = document.createElement('p');
alert(window.getComputedStyle(p, null).getPropertyValue('color'));
will give you the color value, but not add anything to the DOM.
WARNING
After a bit of research, I've determined that this method only works in Gecko-based browsers, so is not suitable for general-purpose use. This situation may change in future, but I wouldn't rely on this if you want a cross-browser solution today.
Given that, I would suggest you just create a temporary element, add the desired class, add it to the document, inspect it to get the style value, then remove it. You can additionally apply styles such as display: none
to prevent it from being shown to the user during the incredibly brief time that it's part of the document.
Short answer: You cannot get a css property from a class that is not applied to any element. However, you can directly read it from a CSS stylesheet and you can do this by using DOM CSS
And then maybe have something like:
var bgimage = myStyleSheet.cssRules[0].style.background-image;
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