Last active
August 29, 2015 14:00
-
-
Save catdad/11222564 to your computer and use it in GitHub Desktop.
Gets the CSS style of a specific query selector and returns it in an object
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
function getStyle(className) { | |
var parseRuleText = function(rule){ | |
var text = rule.split('{').pop().split('}').shift(); | |
var cssRules = {}; | |
var lines = text.split(';'); | |
forEach(lines, function(line){ | |
var rule = line.split(':'); | |
if (rule[0].trim()) cssRules[rule[0].trim()] = rule[1].trim(); | |
}); | |
return cssRules; | |
}; | |
var allCssRules = []; | |
forEach(document.styleSheets, function(sheet){ | |
var classes = sheet.rules || sheet.cssRules; | |
forEach(classes, function(rule){ | |
rule.selectorText && (function(){ | |
var lastSelector = rule.selectorText.split(' ').pop(); | |
if (lastSelector.match(className)){ | |
allCssRules.push( (rule.cssText) ? parseRuleText(rule.cssText, 1) : parseRuleText(rule.style.cssText, 0) ); | |
} | |
})(); | |
}); | |
}); | |
//TODO don't use jQuery here | |
return (allCssRules.length === 1) ? allCssRules.shift() : extend.apply(null, allCssRules); | |
}; | |
// make sure you have a forEach, kids | |
// https://gist.github.com/catdad/11239214 | |
var forEach = function(obj, func, context){ | |
//simple hack, not compatible with old browsers | |
[].forEach.call(obj, function(){ | |
func && func.apply(context, arguments); | |
}) | |
}; | |
//TODO make sure there is an extend function |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment