0

I wrote code that iterates over all the css rules in a page:

function iterateCSS(f) {
  for (const styleSheet of window.document.styleSheets) {
    const classes = styleSheet.rules || styleSheet.cssRules;
    if (!classes) continue;

    for (const cssRule of classes) {
      if (cssRule.type !== 1 || !cssRule.style) continue;
      const selector = cssRule.selectorText, style=cssRule.style;
      if (!selector || !style.cssText) continue;
      for (let i=0; i<style.length; i++) {
        const propertyName=style.item(i);
        if (f(selector, propertyName, style.getPropertyValue(propertyName), style.getPropertyPriority(propertyName), cssRule)===false) return;
      }
    }
  }
}

iterateCSS( (selector, propertyName, propertyValue, propertyPriority, cssRule) => {
  console.log(selector+' { '+propertyName+': '+propertyValue+(propertyPriority==='important' ? ' !important' : '')+' }');
});

However this returns the selector as one string, ie (from gmail):

   html .KA-S-Z .J-Z-M-I-JE, :first-child + html .KA-S-Z .J-Z-M-I-JE

How can I parse cssRule.selectorText (https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleRule/selectorText) into it's separate components ? is there an API for this ? otherwise what would be the best way ? is it sufficient to look for comma delimiters ?

Thx!

kofifus
  • 17,260
  • 17
  • 99
  • 173

0 Answers0