11

i have a same question asked here(wasnt able to comment on it,maybe dont have a priviledge) , i want to get css width value defined in stylesheet but not yet applied on any element in dom ,(its bootstrap css with grid with responsive media queries)

 .span6 {
 width: 570px;
 }

However solution provided in above referenced question return 0 i.e like this

$('<div/>').addClass('span6').width();

but works if i do something like this

 $('<div/>').addClass('span6').hide().appendTo('body').width();

any easy way without appending that div?

Community
  • 1
  • 1
Jaideep Singh
  • 589
  • 2
  • 8
  • 18
  • If you REALLY (really) want to avoid inserting the element, you could make a map with the widths you need :p – leopic Jun 09 '12 at 06:19
  • Why do you want to do that? Maybe there's an alternate / easier way to solve your issue? – Moin Zaman Jun 09 '12 at 06:19
  • The last time I saw a "get style properties with jquery" question it ended up with some regex as accepted answer, I guess your current solution is simple enough. You could call `.remove()` to clean the DOM after getting your desired CSS property value or always have a `display:none` element to apply the CSS to and get the value, removing the applied CSS class afterwards. – Fabrício Matté Jun 09 '12 at 06:35
  • @MoinZaman i want to do some manipulation before deciding that particular class should be added or not, div has a image in it ,its width can be anything – Jaideep Singh Jun 09 '12 at 06:46
  • possible duplicate of [Get CSS properties values for a not yet applied class](http://stackoverflow.com/questions/9382858/get-css-properties-values-for-a-not-yet-applied-class) - I was the author of the original 'bad' answer which has since been updated with more info. – Bobby Jack Jun 13 '12 at 12:24

2 Answers2

29

In order to read a CSS property value from a nonexistent element, you need to dynamically insert that element (as hidden) to the DOM, read the property and finally remove it:

var getCSS = function (prop, fromClass) {

    var $inspector = $("<div>").css('display', 'none').addClass(fromClass);
    $("body").append($inspector); // add to DOM, in order to read the CSS property
    try {
        return $inspector.css(prop);
    } finally {
        $inspector.remove(); // and remove from DOM
    }
};

jsFiddle here

Jose Rui Santos
  • 15,009
  • 9
  • 58
  • 71
4

Great answer by Jose. I modified it to help with more complex css selectors.

var getCSS2 = function (prop, fromClass, $sibling) {

    var $inspector = $("<div>").css('display', 'none').addClass(fromClass);
    if($sibling != null){
        $sibling.after($inspector); //append after sibling in order to have exact 
    } else {
        $("body").append($inspector); // add to DOM, in order to read the CSS property
    }
    try {
        return $inspector.css(prop);
    } finally {
        $inspector.remove(); // and remove from DOM
    }
};

JSFiddle

Biff MaGriff
  • 8,102
  • 9
  • 61
  • 98