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