i have a css and it h开发者_开发知识库as many classes defined in it that are used on various elements
i want that class description to be fetched.. i mean the content of some particular css class. is it possible using js??
It's possible, though it involves looping through the rules of every stylesheet you have in your document until you find a selector that matches the class name, which can be rather slow if you have a large number of styles.
function findClassRule(cls) {
var styles = document.styleSheets,
reg = new RegExp("\\." + cls + "\\s*(?:,|$)"),
res = [];
for (var i=0; i < styles.length; i++) {
var rules = styles[i].cssRules || styles[i].rules;
for (var j=0, max = rules.length; j < max; j++) {
var rule = rules[j];
if (reg.test(rule.selectorText))
res.push(rule.style.cssText);
}
}
return res;
}
Working demo: http://jsfiddle.net/EAf44/ (use your browser's console to view the results).
It will return an array of matching style declarations for the class name you specify. Note that the result declaration might not be the same as what is written in the stylesheet - the browser may have modified it.
The Stylesheet object will give you access to the cssRules. if you know what the selector is you need, then I guess you could iterate over the cssRules until you find a CSSStyleRule with matching selectorText.
精彩评论