Parsing CSS in JavaScript / jQuery

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.

Leave a Comment