Reputation: 1471
I am trying to extract CSS properties from CSSRule
.
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleRule This is a complete CSSRule
object:
CSSStyleRule {
parentRule: null,
parentStyleSheet: CSSStyleSheet { parentStyleSheet: null, cssR
ules: [ [Circular *1] ] },
selectorText: '.one',
style: CSSStyleDeclaration {
'0': 'display',
length: 1,
parentRule: [Circular *1],
_importants: { display: '' },
__starts: 4,
display: 'block'
},
__starts: 0,
__ends: 20
}
I want to extract from this object to this:
{
display: 'block'
}
Is there any good way to extract that object from CSSRule.style
? That object is very messy, and I don't know what props(e.g. display
, color
, font-size
...) will be in that object ahead of time, thus I found it very difficult to extract declarations from there.
Upvotes: 0
Views: 182
Reputation: 19346
To extract the CSS properties of a CSSStyleRule
object you can iterate over the items in it based on its length, get the property name using the item
method, and look up the property value on the style
object.
For simplicity this example uses an HTMLElement's style
property rather than setting up a style sheet and accessing its internals to test the concept.
It also shows that CSS shorthand rules become expanded:
"use strict";
function mapStyle( style) {
const map = {};
for( let i = 0; i < style.length; i++) {
const prop = style.item(i);
map[prop] = style[prop];
}
return map;
}
console.log( mapStyle( document.getElementById("styled").style));
<div id="styled" style="color: red; background-color: black; border: thick solid yellow">
A division with a style property
</div>
Upvotes: 1