Last active
August 17, 2017 11:26
-
-
Save john-doherty/f9e14202687ee760ef41bf71c989ea54 to your computer and use it in GitHub Desktop.
Get all css style blocks matching a css selector from stylesheets
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
/** | |
* Get all CSS style blocks matching a CSS selector from stylesheets | |
* @param {string} className - class name to match | |
* @param {boolean} startingWith - if true matches all items starting with selector, default = false (exact match only) | |
* @example getStylesBySelector('pure-form .pure-form-html ') | |
* @returns {object} key/value object containing matching styles otherwise null | |
*/ | |
function getStylesBySelector(className, startingWith) { | |
if (!className || className === '') throw new Error('Please provide a css class name'); | |
var styleSheets = window.document.styleSheets; | |
var result = {}; | |
// go through all stylesheets in the DOM | |
for (var i = 0, l = styleSheets.length; i < l; i++) { | |
var classes = styleSheets[i].rules || styleSheets[i].cssRules || []; | |
// go through all classes in each document | |
for (var x = 0, ll = classes.length; x < ll; x++) { | |
var selector = classes[x].selectorText || ''; | |
var content = classes[x].cssText || classes[x].style.cssText || ''; | |
// if the selector matches | |
if ((startingWith && selector.indexOf(className) === 0) || selector === className) { | |
// create an object entry with selector as key and value as content | |
result[selector] = content.split(/(?:{|})/)[1].trim(); | |
} | |
} | |
} | |
// only return object if we have values, otherwise null | |
return Object.keys(result).length > 0 ? result : null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment