Created
October 28, 2016 08:53
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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