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}
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With