Skip to content

Instantly share code, notes, and snippets.

@timwburch
Last active October 19, 2017 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timwburch/8b3c5d4c0215eb674c5958265270576d to your computer and use it in GitHub Desktop.
Save timwburch/8b3c5d4c0215eb674c5958265270576d to your computer and use it in GitHub Desktop.
Get CSS Style Property with Javascript
// 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