Skip to content

Instantly share code, notes, and snippets.

@ssafejava
Forked from ydaniv/mozGetMatchedCSSRules.js
Last active November 6, 2022 06:24
Show Gist options
  • Save ssafejava/6605832 to your computer and use it in GitHub Desktop.
Save ssafejava/6605832 to your computer and use it in GitHub Desktop.
// polyfill window.getMatchedCSSRules()
if ( typeof window.getMatchedCSSRules !== 'function' ) {
//TODO: not supporting 2nd argument for selecting pseudo elements
//TODO: not supporting 3rd argument for checking author style sheets only
global.getMatchedCSSRules = function (element /*, pseudo, author_only*/) {
var style_sheets, sheet, sheet_media,
rules, rule,
result = [];
// get stylesheets and convert to a regular Array
style_sheets = [].slice.call(window.document.styleSheets);
while ( sheet = style_sheets.shift() ) {
sheet_media = sheet.media;
// if this sheet is disabled skip it
if ( sheet.disabled ) continue;
// if this sheet's media is specified and is NOT all or screen then skip it
if ( sheet_media.length &&
! (~ sheet_media.indexOf('screen') || ~ sheet_media.indexOf('all')) ) continue;
// get the style rules of this sheet
rules = [].slice.call(sheet.cssRules);
// loop the rules
while ( rule = rules.shift() ) {
//TODO: for now only polyfilling Gecko
// check if this element matches this rule's selector
if ( element.mozMatchesSelector(rule.selectorText) ) {
// push the rule to the results set
result.push(rule);
}
}
}
return result;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment