This should get you all CSS styles that apply to the element. It uses jQuery's is
function to check if a CSS rule selector applies to a given element. Iterate through all stylesheets in document.styleSheets
, and through all cssRules
in each stylesheet, and check if selectorText
matches the element. In pseudocode:
given::element
matchedRules = []
for styleSheet in document.styleSheets
for rule in styleSheet.cssRules
if element.is(rule.selectorText)
matchedRules.push(rule.selectorText)
return matchedRules;
In code:
function getCSSRules(element) {
element = $(element);
var styleSheets = document.styleSheets;
var matchedRules = [], rules, rule;
for(var i = 0; i < styleSheets.length; i++) {
rules = styleSheets[i].cssRules;
for(var j = 0; j < rules.length; j++) {
rule = rules[j];
if(element.is(rule.selectorText)) {
matchedRules.push(rule.selectorText);
}
}
}
return matchedRules;
}
This should return all rules that apply to the element. For your first example, it returns:
[".links-list .title"]
For Nick's extended example, it returns:
[".links-list .title", ".title", "a", "li a"]
How you define specificity and how to decide what to filter out from this list is upto you.