Skip to content

Instantly share code, notes, and snippets.

@ryanc-me
Created October 28, 2016 08:53
Show Gist options
  • Save ryanc-me/ba2cb9815c84380ea643f0f3b847293a to your computer and use it in GitHub Desktop.
Save ryanc-me/ba2cb9815c84380ea643f0f3b847293a to your computer and use it in GitHub Desktop.
Pure JavaScript function to find a CSS rule by it's selector string
function findCssRule(selectorString) {
// helper function searches through the document stylesheets looking for @selectorString
// will also recurse through sub-rules (such as rules inside media queries)
function recurse(node, selectorString) {
if (node.cssRules) {
for (var i = 0; i < node.cssRules.length; i++) {
if (node.cssRules[i].selectorText == selectorString) {
return node.cssRules[i].style;
}
if (node.cssRules[i].cssRules) {
var found = recurse(node.cssRules[i], selectorString);
if (found) return found;
}
}
}
return false;
}
for (var i = 0; i < document.styleSheets.length; i++) {
var sheet = document.styleSheets[i];
if (sheet.cssRules) {
var found = recurse(sheet,selectorString);
if (found) return found;
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment