Last active
October 19, 2020 17:16
-
-
Save paceaux/2b163c39062ec7ed4d78f70d78e5a2fc to your computer and use it in GitHub Desktop.
Get all CSS selectors containing a particular CSS property
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
/** queryCSSByPropertyName | |
* queries the CSSOM looking for CSS rulesets containing a particular CSS property. | |
* @param {string} queryPropName CSS property name | |
* @param {string} queryPropValue value of CSS property | |
* @returns Map with key as CSS selector, value as CSS properties. | |
*/ | |
function queryCSSByProperty(queryPropName, queryPropValue) { | |
const styleSheets= document.styleSheets; // get all the stylesheets | |
const properties = new Map(); // set up the variable that'll store our result | |
if (!queryPropName) return properties; | |
// loop through the stylesheets | |
Object.values(styleSheets).forEach(styleSheet => { | |
// have to wrap in a try because a restricted stylesheet throws an error | |
try { | |
const rules = styleSheet.cssRules; // every styleSheet has an enumerable of rules | |
// loop through the rules in a stylesheet | |
Object.values(rules).forEach(rule => { | |
const {style, selectorText} = rule; | |
if (style) { | |
const propertyValue = style.getPropertyValue(queryPropName); | |
const hasPropValMatch = queryPropValue && propertyValue.indexOf(queryPropValue) !== -1; | |
// wanting exact match of css property value | |
if (queryPropValue && hasPropValMatch) { | |
properties.set(selectorText, `${queryPropName}:${propertyValue}`); | |
} | |
// don't want an exact match of css property value | |
if (!queryPropValue && propertyValue) properties.set(selectorText, `${queryPropName}:${propertyValue}`); | |
} | |
}); | |
} catch (err) { | |
console.log(err); | |
} | |
}); | |
return properties; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment