Reputation: 481
I would like to get the inlines styles set via style attribute as JS object. For e.g in following html I would like to fetch the #box
div styles attribute value as {width: "300px" , color: "red" }
(js object)
HTML
<div id="box" style="width: 300px; color: red">Box</div>
If I directly access the style object of the dom object, the object returned is CSSStyleDeclaration, which is not what I want:
var para = document.getElementById('box')
console.dir(box.style)
Also using window.getComputedStyle()
is not an option because the target object is a clone of a dom element which has not been mounted yet.
Thanks
Upvotes: 0
Views: 44
Reputation: 1946
Here's a different approach that will only give you valid values that the browser understands (instead of simply parsing a string.) This solution iterates over the style object of an element to build the object:
const para = document.getElementById('box')
const styleObj = Array.from(para.style).reduce((style, name) => {
style[name] = para.style[name]
return style
}, {})
The problem with parsing a string and splitting is that any invalid values will also be used. So the example below will give you back { width: 'foobar' }
which is clearly invalid.
<div id="box" style="width: foobar">Box</div>
Upvotes: 2
Reputation: 370639
You can use getAttribute
to get the string attribute, then split by ;
s to turn it into the desired format:
const styleProps = Object.fromEntries(
box.getAttribute('style')
.split(/; +/)
.map(str => str.split(/: */))
);
console.log(styleProps);
<div id="box" style="width: 300px; color: red">Box</div>
Upvotes: 2