I have something like:
const someCSS = ` .foo { padding: 20px; background-color: #ddf; width: 100px; } .bar { height: 100px; } .foo { padding-top: 30px; } `;
I can add this to the DOM and return all selectors with every rule like this ( jsFiddle ):
const style = document.createElement('style'); style.innerHTML = someCSS; document.head.append(style); const styleSheet = Array.from(document.styleSheets).find(ss => ss.ownerNode == style); const rules = Array.from(styleSheet.rules).map(rule => rule.cssText); function styleToObject(rules, mergeWith = {}) { return [...rules].reduce( (obj, rule) => (obj[rule] = rules[rule], obj), mergeWith ); } const styleObject = Array.from(styleSheet.rules).reduce( (obj, rule) => (obj[rule.selectorText] = styleToObject(rule.style, obj[rule.selectorText]), obj), {} ); document.querySelector('pre').appendChild( document.createTextNode(JSON.stringify(styleObject, null, '\t')) );
and get something like this:
{ ".foo": { "padding-top": "30px", "padding-right": "20px", "padding-bottom": "20px", "padding-left": "20px", "background-color": "rgb(221, 221, 255)", "width": "100px" }, ".bar": { "height": "100px" } }
Is there any other way to get the browser to do this without touching the DOM? I mean, CSS text is processed by the browser (without regular expression) without actually styling anything on the page.
Although I am adding it to iFrame, but before adding it to the DOM the document is not available ...
source share