1

edit added a test with regexpr to solve the problem techfoobar pointed out

edit 2 corrected code for others hf :)

I'm looking for a way to get all static styles from a specified class. I don't want to append a new div and extract all possible values from it because values are often just computed...

Here are some related posts:

jQuery CSS plugin that returns computed style of element to pseudo clone that element?

Can jQuery get all CSS styles associated with an element?

http://quirksmode.org/dom/w3c_css.html

This is what i came up so far:

function getExternalCSS(className) {
    var cssText = false;
    $.each(document.styleSheets, function(key, value) {
        $.each(value.cssRules, function(k, v) {
            if(new RegExp(className, "i").test(v.selectorText)) {
                cssText = v.cssText;
                return false;
            }
        });
        if(cssText !== false) {
            return false;
        }
    });
    return cssText;
}

css to browse:

.someClass {
    style1...
}
.someOtherClass {
    style2...
}
.myClassToFind {
    style3...
}

usage:

    getExternalCSS(".myClassToFind");  //note the . for class

The selectorText is returned correctly, but the if is never triggered. I already tried to parse to string etc. Any ideas?

Community
  • 1
  • 1
ChaosClown
  • 367
  • 2
  • 16

1 Answers1

1

Update

Check this demo: http://jsfiddle.net/XaB3T/1/

There were a couple of problems:

a) You need to return false from a $.each to stop the looping, its like break. This was not being done. b) You were checking v.selectorText.toLowerCase() with '.myClass' which surely cannot match since '.myClass' is not all small case


Explanation for For counting in only those styles that will be applied at the end, you might need to do a lot more!

For CSS specificity rules, please refer to:


The if never returns true because:

a) The selector text need not be exactly .yourClass. It can be .a .yourClass, div.yourClass or even .anotherClass, .yourClass etc.. all pointing to your element

b) The check needs to be something like:

for each selectorText {
   strip off any { character
   split the selector text by ',' into an array called parts
   for each part {
      check if it ends with '.yourClass' // if it does, this class is match
   }
}

Another problem is CSS specificity. For counting in only those styles that will be applied at the end, you might need to do a lot more!

techfoobar
  • 65,616
  • 14
  • 114
  • 135
  • i know that this is just a small version and it will need more improvments to cover all classes. but in my testcase the selector was just .myClassToFind so it should match... – ChaosClown Jul 20 '12 at 15:08
  • cant you explain or give a link what you mean by this plz:For counting in only those styles that will be applied at the end, you might need to do a lot more! – ChaosClown Jul 20 '12 at 15:29
  • Pls check my update above. I believe this is what you were looking for. – techfoobar Jul 20 '12 at 15:41