Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get CSS properties values for a not yet applied class

Tags:

jquery

css

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.

like image 559
Manuel Iglesias Avatar asked Feb 21 '12 18:02

Manuel Iglesias


2 Answers

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.

like image 90
Bobby Jack Avatar answered Sep 27 '22 19:09

Bobby Jack


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;
like image 45
wtrevino Avatar answered Sep 27 '22 19:09

wtrevino