spacewindow
spacewindow

Reputation: 407

Get CSS rules into javascript variable

I am wanting to be able to select chunks of CSS Rules using JavaScript or jQuery and get them into a variable, basically as the preformatted text you would expect in a style-sheet.

Ideally we would carefully comment our CSS styles and have them simply in the <head> <style> tag on the html page. The JavaScript would locate the particular comment that wraps the rules within the <style> tag on the page, and copy those rules to a variable as text, for later use.

/* CSS Rules */

.example{
    font-size: 1em;
    color:blue;
}

/* end */

In this case the script would find the string /* CSS Rule */, then select all the lines below it until it hits a terminating comment /* end */

Any ideas? I've googled a fair bit for a solution, but guess this is a pretty unusual thing to be doing, having a hard time finding any pointers.

Upvotes: 0

Views: 342

Answers (2)

user1693593
user1693593

Reputation:

It's a bit hacky-ish, but here is one way to do this -

Extract the text (use regex or indexOf) - assuming you have the text block, create a data-uri out of it:

var cssURL = "data:text/css;charset=utf8," + encodeURIComponent(cssTxt);

create a link element and set rel to stylesheet (browser is able to deal with type):

var link = document.createElement("link");
link.rel= "stylesheet";
link.href = cssURL;

Add to header to load and parse:

document.getElementsByTagName("head")[0].appendChild(link);

Example

Only the green should show -

var css = ".s1 {border:1px solid red} " + 
          "/* start */ .s2 {border:1px solid green} /* end */ " + 
          ".s3 {border:1px solid blue}";

// get css text and convert to data-uri
var start = css.indexOf("/* start */");
var end = css.indexOf("/* end */", start);
var cssTxt = css.substring(start, end);
var cssURL = "data:text/css;charset=utf8," + encodeURIComponent(cssTxt);

// create link element and add to header
var link = document.createElement("link");
link.rel= "stylesheet";
link.href = cssURL;

document.getElementsByTagName("head")[0].appendChild(link);
<div class="s1">Class s1 - ignored</div>
<div class="s2">Class s2 - should have green border</div>
<div class="s3">Class s3 - ignored</div>

Upvotes: 0

JSelser
JSelser

Reputation: 3630

Welp...you could always have an id on your style tag like

<style id="css">div{ background-color:red; }</style>

And then grab the contents with jquery

var cssText = $('#css').html();

But this whole thing would make Ada Lovelace cry, maybe you can find another way to fullfil your requirements?

Upvotes: 2

Related Questions