Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert HTML Element's "Style" Attribute to JSON

I need to convert the style attribute of an HTML element to a JSON object with JavaScript / jQuery. How should I go about this?

Clarification: Lets say I have <div style="font-size: 14px; text-align: center;"></div>, so I want a JSON object: {font-size: 14px, text-align: center}

like image 428
SZH Avatar asked Dec 21 '22 16:12

SZH


1 Answers

How about this:

function getStyles(el) {
    var output = {};

    if (!el || !el.style || !el.style.cssText) {
        return output;
    }

    var camelize = function camelize(str) {
        return str.replace (/(?:^|[-])(\w)/g, function (a, c) {
            c = a.substr(0, 1) === '-' ? c.toUpperCase () : c;
            return c ? c : '';
        });
    }

    var style = el.style.cssText.split(';');

    for (var i = 0; i < style.length; ++i) {
        var rule = style[i].trim();

        if (rule) {
            var ruleParts = rule.split(':');
            var key = camelize(ruleParts[0].trim());
            output[key] = ruleParts[1].trim();
        }
    }

    return output;
}

var element = document.querySelector('div');
var css = getStyles(element);
console.log('css ->', css);

output:

{
    color: "green",
    border: "1px solid orange",
    marginLeft: "15px",
    padding: "20px",
    backgroundColor: "white"
}

fiddle:

https://jsfiddle.net/grt6gkpe/1/

like image 171
Guy Avatar answered Dec 28 '22 01:12

Guy