I would like to know an easy way to get all the css rules and classes on a certain DOM node and the subtree programmatically.
Chrome Dev Tools
Inspecting the style of an element in the chrome dev tools returns 2 panels
- Computed Style
- Styles
The Styles-Panel has 3 different style categories:
- element.style
- Matched CSS Rules
- inherited from ….
The function window.getMatchedCSSRules comes quite close to the panel Matched CSS Rules in the dev-tools.
I want to iterate over an element and its children and add the matched css rules to a string.
This updated fiddle explains and demonstrates the expected and the unwanted result
Example:
<a class="one to many">
<span class="even more">foo</span>
<span class="way muchMore"> bar</span>
</a>
How can i get all the css-classes with the stylerules like this
a.one { color: red; }
.to { margin: 2em}
And so on. The following function comes quite close to the expected result:
// el = a DOM-Node document.getElementById(id);
function getCssText(el) {
var cssText = "";
var cssRuleList = window.getMatchedCSSRules(el, '');
for (var i = 0; i < cssRuleList.length; i++) {
cssText += cssRuleList[i].cssText + " ";
}
return cssText;
}
Alexander pointed to this discussion about window.getMatchedCSSRules() returning null
Does anyone have a plugin or a more sophisticated function for me to retrieve the css classes and the values of a domnode?
What prevents you from mouse-selecting and copying (Ctrl-C, whatever) the contents of the “Matched CSS Rules” or “Computed Styles” section in the sidebar (am I missing the task you are trying to solve?)
There’s a known issue with pasting the copied contents into well-known HTML-aware text editors (the CSS properties inside rules are rendered as a numbered list, which is actually a bug in the respective editors) but otherwise, if you want to manually grab a copy of all your matched CSS rules/computed style for a DOM element, this workflow should work for you.
3rd party edit
In the comment below it is recommended to use
window.getMatchedCSSRules(). Using it in Chrome 62 returns thisThe discussion getMatchedCSSRules was started in november 2014 and contains this bit
getMatchedCSSRules is non-standard and likely to be removed in the coming months. Relying on it is bad for cross-browser interop since major browsers like Firefox and IE won't be supported.It seems that M63 will start to remove it.An alternative might be to use CSS Object Model (CSSOM)