In fact you can only do this using native JS. jQuery does not support methods to deal with CSS rules traversing. Firstly you have to loop through all the document.styleSheets
, in each sheet, you have to loop through all the sheet.cssRules
. Each CssRule
has a property called selectorText
, you can get this and compare against your rule text. However you need to care about the order of identifiers in the selector path here. Here is the demo code:
var rulesChecker = {
compactRuleText: function(text) {
return text.replace(/[.#][^ +~>]+/g,
function(m){
return m.split(/([.#][^.#]+)/).sort().join('');
})
.replace(/(\s*?[>+~]\s*|\s+?(?=\s))/g, function(m){
return m.trim();
});
},
ruleExistence : [],
init : function(){
var sheets = document.styleSheets;
for(var i = 0; i < sheets.length; i++){
var rules = sheets[i].cssRules || sheets[i].rules;
for(var j = 0; j < rules.length; j++){
var a = this.compactRuleText(rules[j].selectorText);
this.ruleExistence[a] = true;
}
}
},
ruleExists : function(ruleText) {
var key = this.compactRuleText(ruleText);
return (key in this.ruleExistence);
}
};
rulesChecker.init();
//your rule text, note about the extra spaces and how close the identifiers are ...
//this in fact should match the rule in the CSS code (which is normally written)
var ruleText = ".f+.a.b#e > .d .k";
//ruleText = ".c";
alert(rulesChecker.ruleExists(ruleText));