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?
Update
Check this demo: http://jsfiddle.net/XaB3T/1/
There were a couple of problems:
a) You need to
return falsefrom a$.eachto stop the looping, its likebreak. This was not being done.b) You were checking
v.selectorText.toLowerCase()with'.myClass'which surely cannot match since'.myClass'is not all small caseExplanation 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
ifnever returns true because:a) The selector text need not be exactly
.yourClass. It can be.a .yourClass,div.yourClassor even.anotherClass, .yourClassetc.. all pointing to your elementb) The check needs to be something like:
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!