Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

jquery - Access CSS file contents via JavaScript

Is it possible to get the entire text content of a CSS file in a document? F.ex:

<link rel="stylesheet" id="css" href="/path/to/file.css">
<script>
    var cssFile = document.getElementById('css');
    // get text contents of cssFile
</script>

I’m not really into getting all the CSS rules via document.styleSheets, is there another way?

Update: There is the ajax option of course, I appreciate the answers given. But it seems rather unnecessary to reload a file using ajax that is already loaded in the browser. So if anyone knows another way to extract the text contents of a present CSS file (NOT the CSS rules), please post!

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

With that specific example (where the CSS is on the same origin as the page), you could read the file as text via ajax:

$.ajax({
    url: "/path/to/file.css",
    dataType: "text",
    success: function(cssText) {
        // cssText will be a string containing the text of the file
    }
});

If you want to access the information in a more structured way, document.styleSheets is an array of the style sheets associated with the document. Each style sheet has a property called cssRules (or just rules on some browsers), which is an array of the text of each rule in the style sheet. Each rule has a cssText property. So you could loop through those, e.g.:

$.each(document.styleSheets, function(sheetIndex, sheet) {
    console.log("Looking at styleSheet[" + sheetIndex + "]:");
    $.each(sheet.cssRules || sheet.rules, function(ruleIndex, rule) {
        console.log("rule[" + ruleIndex + "]: " + rule.cssText);
    });
});

Live example - That example has one stylesheet with two rules.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...