Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

javascript - Getting all css used in html file

I have to get what are all the CSS styles used in a HTML file using JavaScript.

<html>
    <head>
        <style type="text/css">
            body {
                border: 1px solid silver;
            }
            .mydiv{
                color: blue;
            }
        </style>
    </head>
    <body>
    </body>
</html>

If the above code is my HTML I have to write one JavaScript function inside the head which returns a string like this.

body {
    border: 1px solid silver;
}
.mydiv {
    color: blue;
}

Is it possible to do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For inline stylesheets, you can get the content out of the normal DOM like with any other element:

document.getElementsByTagName('style')[0].firstChild.data

For external, linked stylesheets it's more problematic. In modern browsers, you can get the text of every rule (including inline, linked and @imported stylesheets) from the document.styleSheets[].cssRules[].cssText property.

Unfortunately IE does not implement this DOM Level 2 Style/CSS standard, instead using its own subtly different version of the StyleSheet and CSSRule interfaces. So you need some sniff-and-branch code to recreate rules in IE, and the text might not be exactly the same as the original. (In particular, IE will ALL-CAPS your property names and lose whitespace.)

var css= [];

for (var sheeti= 0; sheeti<document.styleSheets.length; sheeti++) {
    var sheet= document.styleSheets[sheeti];
    var rules= ('cssRules' in sheet)? sheet.cssRules : sheet.rules;
    for (var rulei= 0; rulei<rules.length; rulei++) {
        var rule= rules[rulei];
        if ('cssText' in rule)
            css.push(rule.cssText);
        else
            css.push(rule.selectorText+' {
'+rule.style.cssText+'
}
');
    }
}

return css.join('
');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...