Skip to content

Instantly share code, notes, and snippets.

@acatl
Last active August 29, 2015 14:22
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 acatl/c38da5c9392fab35896a to your computer and use it in GitHub Desktop.
Save acatl/c38da5c9392fab35896a to your computer and use it in GitHub Desktop.
find ALL matching styles with matching values on a document
/*
* credit of `getMatchedStyle` method for stakoverflow's Qtax
* http://stackoverflow.com/questions/9730612/get-element-css-property-width-height-value-as-it-was-set-in-percent-em-px-et/9733051#9733051
*/
function getMatchedStyle(elem, property) {
// element property has highest priority
var val = elem.style.getPropertyValue(property);
// if it's important, we are done
if (elem.style.getPropertyPriority(property))
return val;
// get matched rules
var rules = getMatchedCSSRules(elem);
// iterate the rules backwards
// rules are ordered by priority, highest last
for (var i = rules.length; i-- > 0; ) {
var r = rules[i];
var important = r.style.getPropertyPriority(property);
// if set, only reset if important
if (val == null || important) {
val = r.style.getPropertyValue(property);
// done if important
if (important)
break;
}
}
return val;
}
function findStyle(style) {
var matches = [];
$('*').each(function(index, element) {
var val = getMatchedStyle(element, style.property);
if (val && style.match.test(val)) {
matches.push([style, val, element]);
}
});
return matches;
}
function findStyles(styles) {
return styles.map(function(style, index) {
var results = findStyle(style);
return {
style: style,
results: results
}
});
}
function printResults(results){
results.forEach(function(style){
style.results.forEach(function(result){
console.log(result[0], result[1], result[2]);
});
});
}
@acatl
Copy link
Author

acatl commented Jun 3, 2015

implement:

var matchingStyles = findStyles([{
    property: 'width',
    match: /(vh|vw)/
},{
    property: 'height',
    match: /(vh|vw)/
},{
    property: 'margin',
    match: /(vh|vw)/
},{
    property: 'padding',
    match: /(vh|vw)/
}]);

printResults(matchingStyles);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment