Is there a way to extract only the applied CSS rules to a DOM node using JavaScript?
I am familiar with getComputedStyle
, but it retrieves all styles, not just those applied from stylesheets, inline styles, or injected into the CSSOM.
The technique I have seen involves copying HTML in a browser and pasting it into a contenteditable field. The pasted HTML contains only the relevant styles inlined on the node along with class names. It seems like magic! How does this process work? Does the browser automatically inline the applied styles during the copy action?
I am considering trying something like this:
const get_relevant_styles = function(el) {
const vanilla = document.createElement(el.tagName)
return diff_properties(getComputedStyle(vanilla), getComputedStyle(el))
}
However, implementing this for every node appears to be very resource-intensive. I wonder if the browser has a smarter solution, possibly by interacting directly with the CSSOM. Any insights on this would be greatly appreciated :)