Reputation: 3812
I'm trying to find a way to extract all css rules from any given element (I have full access to the html, and css).
I have look into other solutions such as getComputedStyle, however, it doesn't help much with certain properties such as width or height. For example, I expect it to return width: 100% when applicable, but it always return the real width value in px. What I need is the CSS rule definition, not how it is actually rendered on the browser.
My last resort is to use some css-inliner such as juicejs then I can access the element.style.prop, but I think if these js inliners can turn css rules to inline css then they must have extracted the css rules along the way already? I tried to look into its source but if there is any module out there doing the job it would be much better than trying to extract the code from that library.
Upvotes: 1
Views: 818
Reputation: 3812
It amazes me that there are not many solutions available for this issue. I ended up finding 2 solutions that both work (there are probably some edge cases but I have not encountered yet)
Option 1: A getMatchedCSSRules implementation posted here: https://stackoverflow.com/a/37958301/821517
Pros: short and concise
Cons: does not support pseudo selectors (yet)
Option 2: A very all library called CSSUtilities mentioned here: https://stackoverflow.com/a/12023174/821517
Pros: it can handle pseudo selectors
Cons: very very old library which relies on another library that is deprecated.
I ended up using CSSUtilities and I had to make some changes (hacks) to make it work with the new js engines. I post both modified files here in hope that it will help others (and that errors I made can be spotted and suggested with fixes)
Upvotes: 3