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 :)

jiangts
  • 78
  • 1
  • 8
  • Maybe? https://developer.mozilla.org/en-US/docs/Web/API/CSSRuleList – EGC Oct 03 '19 at 23:16
  • ok, I found https://stackoverflow.com/questions/2952667/find-all-css-rules-that-apply-to-an-element that gets me way closer than getComputedStyle. The issue is: 1. stylesheets can be blocked by CORS rules 2. I still need to manually compute CSS selector specificity, perhaps I can use getMatchedCSSRules . – jiangts Oct 03 '19 at 23:43

1 Answers1

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!

jiangts
  • 78
  • 1
  • 8