1

I want to get all applied CSS rules to a DOM node with JavaScript.

I know that getComputedStyle exists, but that returns ALL styles, not just styles applied from stylesheets / inline styles / styles injected into the CSSOM.

The only way I've seen this work is by copying HTML on a browser, and pasting it into a contenteditable field. The pasted HTML magically includes only the relevant styles inlined on the node, and the class names. I'd be interested to see how that works. Does the browser inline the applied styles during copy for you? If so, how does it do that?

I guess I can try something like

const get_relevant_styles = function(el) {
  const vanilla = document.createElement(el.tagName)
  return diff_properties(getComputedStyle(vanilla), getComputedStyle(el))
}

but doing that for every node seems super expensive. I'm guessing the browser does something smarter, perhaps by dealing with the CSSOM directly? Any insight appreciated :)

2

1 Answer 1

1

It looks like this can be solved with the following library!

http://www.brothercake.com/site/resources/scripts/cssutilities/

I'm not sure if it solves the stylesheets blocked by CORS issue, but it computes CSS selector specificity and overrides for you!

Sign up to request clarification or add additional context in comments.

Comments

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.