keepyourweb
keepyourweb

Reputation: 662

JavaScript CSS parser

I'm searching a css parser for javascript that works like jquery, example:

var style = {

    '.test': {
        paddingTop: 20,
        height: 100,
        width: 100,
        borderRadius: 5
    },

    '.test2': {
        color: '#888'
    }

}

this json must be convert in:

.test{
    padding-top: 20px;
    height: 100px;
    width: 100px;
    border-radius: 5px;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
}   
.test2 {
    color: #888;
}

thanks!

Upvotes: 1

Views: 343

Answers (1)

David Hedlund
David Hedlund

Reputation: 129782

Something simple.

Replaces all camelCase to css-hyphenation (props to @AKX for better regex).

String.prototype.toCssProperty = function () {
    return this.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
};

Appends px to all numeric values.

if(typeof value === 'number')
    value += 'px';

Demo

function addRule(selector, styles) {
    var builder = [];
    for(var key in styles) {
        if(styles.hasOwnProperty(key)) {

            var value = styles[key];
            if(typeof value === 'number')
                value += 'px';

            builder.push(key.toCssProperty() + ':' + value);
        }
    }       

    var rule = builder.join('; ');
    document.styleSheets[0].addRule(selector,rule);
}

function applyStyles(s) {
    for(var key in s) {
        if(s.hasOwnProperty(key)) {
            addRule(key, s[key]);            
        }
    }
};

If you just want the string, you should return that, instead of adding the css rule, as I'm doing in the demo.

I'm sure there are heaps of corner-cases that this doesn't cover. Implement with care.

Upvotes: 2

Related Questions