Search code examples
javascriptjquerycssparsing

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!


Solution

  • There is a CSS parser written in Javascript called JSCSSP