Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing CSS in JavaScript / jQuery

I'm trying to implement parsing of CSS in JavaScript so that:

a {   color: red; } 

is parsed into the object:

{   'a' {     'color': 'red'   } } 

First off, is there a JavaScript / jQuery library I can use?

My implementation is pretty basic, so I'm sure it is not fool-proof by any means. For example, it works fine for basic CSS, but for a property of the type:

background: url(data:image/png;base64, ....); 

It fails because I am using split(';') to separate property:value pairs. Here, ; occurs in the value, so it splits at that point too.

Is there an alternate way to do this?

Here is the code:

parseCSS: function(css) {     var rules = {};     css = this.removeComments(css);     var blocks = css.split('}');     blocks.pop();     var len = blocks.length;     for (var i = 0; i < len; i++)     {         var pair = blocks[i].split('{');         rules[$.trim(pair[0])] = this.parseCSSBlock(pair[1]);     }     return rules; },  parseCSSBlock: function(css) {      var rule = {};     var declarations = css.split(';');     declarations.pop();     var len = declarations.length;     for (var i = 0; i < len; i++)     {         var loc = declarations[i].indexOf(':');         var property = $.trim(declarations[i].substring(0, loc));         var value = $.trim(declarations[i].substring(loc + 1));          if (property != "" && value != "")             rule[property] = value;     }     return rule; },  removeComments: function(css) {     return css.replace(/\/\*(\r|\n|.)*\*\//g,""); } 

Thanks!

like image 836
ankit Avatar asked Jul 24 '10 19:07

ankit


2 Answers

You can easily use the Browser's own CSSOM to parse CSS:

var rulesForCssText = function (styleContent) {     var doc = document.implementation.createHTMLDocument(""),         styleElement = document.createElement("style");     styleElement.textContent = styleContent;     // the style will only be parsed once it is added to a document     doc.body.appendChild(styleElement);      return styleElement.sheet.cssRules; }; 

For each rule returned you can look at the properties in rule.style. See http://jsfiddle.net/v2JsZ/ for an example.

like image 189
cburgmer Avatar answered Sep 19 '22 08:09

cburgmer


There is a CSS parser written in Javascript called JSCSSP

like image 44
Matthew Manela Avatar answered Sep 20 '22 08:09

Matthew Manela