Short version April 12, 2017
Challenger will appear.
var getMatchedCSSRules = (el, css = el.ownerDocument.styleSheets) => [].concat(...[...css].map(s => [...s.cssRules||[]])) .filter(r => el.matches(r.selectorText));
Line /* 1 */ builds a flat array of all the rules.
The line /* 2 */ cancels the rules of non-compliance.
Based on function css(el) by @SB on the same page.
Example 1
var div = iframedoc.querySelector("#myelement"); var rules = getMatchedCSSRules(div, iframedoc.styleSheets); console.log(rules[0].parentStyleSheet.ownerNode, rules[0].cssText);
Example 2
var getMatchedCSSRules = (el, css = el.ownerDocument.styleSheets) => [].concat(...[...css].map(s => [...s.cssRules||[]])) .filter(r => el.matches(r.selectorText)); function Go(big,show) { var r = getMatchedCSSRules(big); PrintInfo: var f = (dd,rr,ee="\n") => dd + rr.cssText.slice(0,50) + ee; show.value += "--------------- Rules: ----------------\n"; show.value += f("Rule 1: ", r[0]); show.value += f("Rule 2: ", r[1]); show.value += f("Inline: ", big.style); show.value += f("Computed: ", getComputedStyle(big), "(β¦)\n"); show.value += "-------- Style element (HTML): --------\n"; show.value += r[0].parentStyleSheet.ownerNode.outerHTML; } Go(...document.querySelectorAll("#big,#show"));
.red {color: red;} #big {font-size: 20px;}
<h3 id="big" class="red" style="margin: 0">Lorem ipsum</h3> <textarea id="show" cols="70" rows="10"></textarea>
Omissions
- No multimedia processing, no
@import , @media . - There is no access to styles loaded from cross-domain style sheets.
- There is no sorting by the "specificity" of the selector (order of importance).
- No styles inherited from parents.
- May not work with old or rudimentary browsers.
- Not sure how he handles pseudo-classes and pseudo-selectors, but everything seems to be in order.
Perhaps one day I will consider these shortcomings.
Long version May 4, 2017
There is a much more complete implementation, taken from the someones GitHub page (the original code forked from this, via Bugzilla ), written for Gecko and IE, but it is rumored to also work with Blink.
May 4, 2017: The specificity calculator had critical errors, which I have now fixed. (I cannot notify the authors because I do not have a GitHub account.)
// polyfill window.getMatchedCSSRules() in FireFox 6+ if (typeof window.getMatchedCSSRules !== 'function') { var ELEMENT_RE = /[\w-]+/g, ID_RE = /
Bugs fixed
= match β += matchreturn re ? re.length : 0; β return matches ? matches.length : 0; return matches ? matches.length : 0;_matchesSelector(element, selector) β matchesSelector(element, selector)
7vujy0f0hy Jun 22 '16 at 3:58 2016-06-22 03:58
source share