Skip to content

Instantly share code, notes, and snippets.

@AymaneD
Forked from ZER0/gist:5267608
Created June 25, 2020 09:02
Show Gist options
  • Select an option

  • Save AymaneD/c7f0c8b7edd85c7d3b7297221bdae48d to your computer and use it in GitHub Desktop.

Select an option

Save AymaneD/c7f0c8b7edd85c7d3b7297221bdae48d to your computer and use it in GitHub Desktop.

Revisions

  1. @ZER0 ZER0 revised this gist Mar 28, 2013. No changes.
  2. @ZER0 ZER0 created this gist Mar 28, 2013.
    36 changes: 36 additions & 0 deletions gistfile1.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    var proto = Element.prototype;
    var slice = Function.call.bind(Array.prototype.slice);
    var matches = Function.call.bind(proto.matchesSelector ||
    proto.mozMatchesSelector || proto.webkitMatchesSelector ||
    proto.msMatchesSelector || proto.oMatchesSelector);

    // Returns true if a DOM Element matches a cssRule
    var elementMatchCSSRule = function(element, cssRule) {
    return matches(element, cssRule.selectorText);
    };

    // Returns true if a property is defined in a cssRule
    var propertyInCSSRule = function(prop, cssRule) {
    return prop in cssRule.style && cssRule.style[prop] !== "";
    };

    // Here we get the cssRules across all the stylesheets in one array
    var cssRules = slice(document.styleSheets).reduce(function(rules, styleSheet) {
    return rules.concat(slice(styleSheet.cssRules));
    }, []);

    // Example of usage:

    // get a reference to an element, then...
    var bar = document.getElementById("bar");

    // get only the css rules that matches that element
    var elementRules = cssRules.filter(elementMatchCSSRule.bind(null, bar));

    // check if the property "width" is in one of those rules
    hasWidth = propertyInCSSRule.bind(null, "width");

    // Do something if `width` is defined in the element's rules
    if (elementRules.some(hasWidth)) {
    // ...
    }