简体   繁体   中英

read css file from HTML throws error

I have the below code to read and append to a div tag.(I have a requirement to implement this.)

var totalCss= "\n";
    var requiredSheets = ['test.css']; 
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
    for (var s = 0; s <= classes.length; s++) {
        var cssRules = document.styleSheets[s].cssRules ||
                document.styleSheets[s].rules || []; 
        for (var c = 0; c < cssRules.length; c++) {
            totalCss+= (cssRules[c].cssText + '\n');
        }
    }

Test.css is in the same folder of HTML.

My test.css have the below properties.(this is just sample)

.test triangle {

    stroke: #000;
    stroke-opacity: .75;
    shape-rendering: crispEdges;
}

.test square {
    stroke-opacity: .75;
}

.test circle {
    stroke-opacity: 0;
}

.test .line {
    fill: none; 

}

When I run the snippet I'm getting

No rules defined error

. If the styles are embedded in the same html file, the properties are able to fetch by the code. But external files referenced in the html is not recognizing by the code.What may the cause?

Sample

In this alert returns null.

Edit:

To my surprise the same code is working fine in Mozilla but showing cssrules null in chrome.

There are multiple stylesheets with a document. So you have to loop all the stylesheets.

Below is the working example

Update 1

Added ajax to get the external css linked with the page

 var style = "\\n"; for (var s = 0; s < document.styleSheets.length; s++) { var cssRules = document.styleSheets[s].cssRules || document.styleSheets[s].rules || []; // IE support for (var c = 0; c < cssRules.length; c++) { style += (cssRules[c].cssText + '\\n'); } } console.log(style); //Request for each external css $("link").each(function() { if (this.href) { $.get(this.href, function(css) { console.log(css); }); } });
 .box { position: absolute; background-color: red; height: 10px; width: 10px; } #car, .car { position: absolute; background-color: red; height: 11px; width: 10px; } }
 <link href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.4/nv.d3.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM