How can you determine if a css class exists with Javascript?

前端 未结 10 1017
闹比i
闹比i 2020-11-27 04:14

Is there a way to determine whether or not a css class exists using JavaScript?

10条回答
  •  遥遥无期
    2020-11-27 04:28

    Based on the answer, I created a javascript function for searching for a CSS class in the browser's memory -

    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) {}
      }
    };
    
    searchForCss('my-class-name');
    

    This will print a line for each occurrence of the class name in any of the rules in any of the stylesheets.

    Ref - Search for a CSS class in the browser memory

提交回复
热议问题