CSS and javascript books

Recently I found myself working on a very messy web application written in react. There were multiple CSS files linked to the HTML index file using the link tag. Also multiple other CSS files linked in the JS files which would then be processed by css-loader and style-loader.

It became very difficult to figure out if a class was loaded into the browser’s memory, whether it was defined internally or in a linked stylesheet.

I ended up writing a javascript function to search for a class name in any of the stylesheets of the loaded document. The function is based on one of the answers I found on stackoverflow.

var searchForCss = function (searchClassName) {
  for (let i = 0; i < document.styleSheets.length; i++) {
    let styleSheet = document.styleSheets[i];
    try {
      for (let j = 0; j < styleSheet.cssRules.length; j++) {
        let rule = styleSheet.cssRules[j];
        // console.log(rule.selectorText)
        if (rule.selectorText && rule.selectorText.includes(searchClassName)) {
          console.log('found - ', rule.selectorText, ' ', i, '-', j);
        }
      }
      if (styleSheet.imports) {
        for (let k = 0; k < styleSheet.imports.length; k++) {
          let imp = styleSheet.imports[k];
          for (let l = 0; l < imp.cssRules.length; l++) {
            let rule = imp.cssRules[l];
            if (
              rule.selectorText &&
              rule.selectorText.includes(searchClassName)
            ) {
              console.log('found - ',rule.selectorText,' ',i,'-',k,'-',l);
            }
          }
        }
      }
    } catch (err) {}
  }
};

You can pass the class name to the above function to search for it in the browser’s memory.

searchForCss() function in action to search for a css class in the current browser memory
Screenshot of the function in action on my blog

Leave a Reply

Your email address will not be published. Required fields are marked *