Last active
October 19, 2017 22:33
-
-
Save timwburch/8b3c5d4c0215eb674c5958265270576d to your computer and use it in GitHub Desktop.
Get CSS Style Property with Javascript
This file contains hidden or 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
// This function will return css text of a supplied css selector (must match exactly) or | |
// it will return the property defined in the second argument. Properties are individual | |
// properties not combined properties. | |
// | |
// propertyFromStylesheet('some selector', 'some property'); | |
// | |
// modified from http://stackoverflow.com/a/16779622 | |
function propertyFromStylesheet() { | |
var value; | |
// Checks for Selector argument. | |
if (typeof(arguments[0]) === 'undefined') throw "Error: no selector defined"; | |
var selector = arguments[0]; | |
//Checks for attribute. If undefined cssText is returned. | |
var attribute = (typeof(arguments[1]) != 'undefined') ? arguments[1] : null; | |
[].some.call(document.styleSheets, function (sheet) { | |
return [].some.call(sheet.rules, function (rule) { | |
if (selector === rule.selectorText) { | |
if (attribute) { | |
return [].some.call(rule.style, function (style) { | |
if (attribute && attribute === style) { | |
value = rule.style.getPropertyValue(attribute); | |
return true; | |
} | |
return false; | |
}); | |
} else { | |
value = rule.cssText; | |
return true; | |
} | |
} | |
return false; | |
}); | |
}); | |
return value; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment