Skip to content

Instantly share code, notes, and snippets.

@ZER0
Last active April 26, 2023 17:26
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save ZER0/5267608 to your computer and use it in GitHub Desktop.
Save ZER0/5267608 to your computer and use it in GitHub Desktop.
Find all the CSS rules applied to a specific element; and check if a CSS property for a specific element is defined in the stylesheet – not inline style. Notice that is not like `getComputedStyle`, that returns the calculated properties for a specific element.
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)) {
// ...
}
@mimalef70
Copy link

i get an error:
Uncaught DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment