1

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.

7

1 Answer 1

3

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)

  1. New files: https://gist.github.com/yellow1912/c9dbbab97497ec42489be55e8abe73c7
  2. Please ensure that you visit this link to download the package which contains the document file: http://www.brothercake.com/site/resources/scripts/cssutilities/
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for creating that gist - and updating it! The download link is broken on the official site and it would be a shame if this gets lost. I think you can skip Selector.js since the api option is false by default so the browser will fall back to its own selector API. This used to be required to support really old browsers but is not needed these days.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.