Get Index Of A Css Rule By Name
I am trying to find the index of a css rule .widget-area in a stylesheet. This is how I'm doing it, but it returns undefined: function findStyle(){ var myStylesheet=document.styleS
Solution 1:
getStyleRuleIndexBySelector
function will find the index of a specific rule. Take into account that this searches by selector only, and there could be more than one rules per selector.
// create a dummy stylesheet which we'll search a key by valuevar style = document.createElement("style")
style.appendChild(document.createTextNode(""))
document.head.appendChild(style);
// insert some rules
style.sheet.insertRule('.first{ color:red }', style.sheet.cssRules.length);
style.sheet.insertRule('.second{ color:green }', style.sheet.cssRules.length);
style.sheet.insertRule('div span a{ color:blue }', style.sheet.cssRules.length);
style.sheet.insertRule('.second{ display:none; left:1px; }', style.sheet.cssRules.length);
// get the rulesvar rules = style.sheet.cssRules;
functiongetStyleRuleIndexBySelector(selector, prop){
var result = [], i,
value = (prop ? selector + "{" + prop + "}" : selector).replace(/\s/g, ''), // remove whitespaces
s = prop ? "cssText" : "selectorText";
for( i=0; i < rules.length; i++ )
if( rules[i][s].replace(/\s/g, '') == value)
result.push(i);
return result;
}
console.log( getStyleRuleIndexBySelector('.second' ) );
console.log( getStyleRuleIndexBySelector('.second', 'display:none; left:1px;') );
Solution 2:
I think you are using .cssRules as a function but it is an object. So if you want to look for a custom rule you should use something like this:
var targetRule;
var rules = document.styleSheets[8].cssRules;
for (i=0; i<rules.length; i++){
if (rules[i].selectorText.toLowerCase() == ".widget-area"){
targetRule = rules[i];
break;
}
}
Post a Comment for "Get Index Of A Css Rule By Name"