CSSify

by nathan

HTML

<b>Text</b>

CSS

p {}
b {
    color: #00ff00;
}
a {}

JavaScript

/*

Bugs:
* removes styles already defined in stylesheet
* removes rule-sets after the selector in question
* adds an empty rule at end of rule-set

*/

(function ($) {
    $.fn.cssify = function (stylesheet) {
        // jQuery plugin which takes the "style" attribute of the first element in the collection
        // and puts it into the chosen stylesheet.
        //
        // For it to work, you must choose your elements using only a selector: $('p>a') instead
        // of $('p').children('a'). The selector must be valid CSS for all browsers used by your
        // target audience, as you lose the advantages of jQuery's abstraction.
        //
        var parseRuleSet,
            fullText = $(stylesheet).html(),
            selector = this.selector,
            i,
            j,
            splitText,
            ruleSets = [],
            rules = [],
            propVal;
        parseRuleSet = function (ruleSet) {
            var ruleObj = {},
                i;
            if (ruleSet === null || ruleSet === undefined) {
                return {};
            }
            // remove braces (if any) then split into separate rules
            ruleSet = ruleSet.replace(/\{\s*|\s*\}/gm, "")
                .split(/\s*;\s*/gm);
            for (i in ruleSet) {
                propVal = ruleSet[i].split(':');
                ruleObj[$.trim(propVal.shift())] = $.trim(propVal.join(':'));
            }
            return ruleObj;
        };
        splitText = fullText.split(selector);

        /*
        Set up the rules array. It takes this format:
            rules = [
                {
                    cssProperty1: value1,
                    cssProperty2: value2
                }
            ];
        The array is to account for the possibility for multiple identical selectors in a single stylesheet.
        */
        
        // ignore the first element as that's everything before the selector we need
        for (i = 1; i < splitText.length; i++) {
   ...