Skip to content

Instantly share code, notes, and snippets.

@paceaux paceaux/queryCSSProperty
Last active Jun 30, 2019

Embed
What would you like to do?
Get all CSS selectors containing a particular CSS property
/** 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
You can’t perform that action at this time.