开发者

css and javascsript

开发者 https://www.devze.com 2023-02-01 02:54 出处:网络
i have a css and it h开发者_开发知识库as many classes defined in it that are used on various elements

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消