Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

like image 606
gidmanma Avatar asked Jun 11 '09 20:06

gidmanma


People also ask

Which method is used to check class exist or not?

Method 1: Using hasClass() method: The hasClass() is an inbuilt method in jQuery which check whether the elements with the specified class name exists or not. It returns a boolean value specifying whether the class exists in the element or not.

How do you check whether the class is present or not in jQuery?

The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".


7 Answers

This should be possible to do using the document.styleSheets[].rules[].selectorText and document.styleSheets[].imports[].rules[].selectorText properties. Refer to MDN documentation.

like image 101
Helen Avatar answered Oct 05 '22 15:10

Helen


function getAllSelectors() { 
    var ret = [];
    for(var i = 0; i < document.styleSheets.length; i++) {
        var rules = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
        for(var x in rules) {
            if(typeof rules[x].selectorText == 'string') ret.push(rules[x].selectorText);
        }
    }
    return ret;
}


function selectorExists(selector) { 
    var selectors = getAllSelectors();
    for(var i = 0; i < selectors.length; i++) {
        if(selectors[i] == selector) return true;
    }
    return false;
}
like image 20
Cau Guanabara Avatar answered Oct 05 '22 15:10

Cau Guanabara


Here is my solution to this. I'm essentially just looping through document.styleSheets[].rules[].selectorText as @helen suggested.

/**
 * This function searches for the existence of a specified CSS selector in a given stylesheet.
 *
 * @param (string) styleSheetName - This is the name of the stylesheet you'd like to search
 * @param (string) selector - This is the name of the selector you'd like to find
 * @return (bool) - Returns true if the selector is found, false if it's not found
 * @example - console.log(selectorInStyleSheet ('myStyleSheet.css', '.myClass'));
 */    

function selectorInStyleSheet(styleSheetName, selector) {
    /*
     * Get the index of 'styleSheetName' from the document.styleSheets object
     */
    for (var i = 0; i < document.styleSheets.length; i++) {
        var thisStyleSheet = document.styleSheets[i].href ? document.styleSheets[i].href.replace(/^.*[\\\/]/, '') : '';
        if (thisStyleSheet == styleSheetName) { var idx = i; break; }
    }
    if (!idx) return false; // We can't find the specified stylesheet

    /*
     * Check the stylesheet for the specified selector
     */
    var styleSheet = document.styleSheets[idx];
    var cssRules = styleSheet.rules ? styleSheet.rules : styleSheet.cssRules;
    for (var i = 0; i < cssRules.length; ++i) {
        if(cssRules[i].selectorText == selector) return true;
    }
    return false;
}

This function offers a speed improvement over other solutions in that we are only searching the stylesheet passed to the function. The other solutions loop through all the stylesheets which is in many cases unnecessary.

like image 30
circuitry Avatar answered Oct 05 '22 16:10

circuitry


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

like image 37
Nithin Kumar Biliya Avatar answered Oct 05 '22 17:10

Nithin Kumar Biliya


/* You can loop through every stylesheet currently loaded and return an array of all the defined rules for any selector text you specify, from tag names to class names or identifiers.

Don't include the '#' or '.' prefix for an id or class name.

Safari used to skip disabled stylesheets, and there may be other gotchas out there, but reading the rules generally works better across browsers than writing new ones. */

function getDefinedCss(s){
    if(!document.styleSheets) return '';
    if(typeof s== 'string') s= RegExp('\\b'+s+'\\b','i'); // IE capitalizes html selectors 

    var A, S, DS= document.styleSheets, n= DS.length, SA= [];
    while(n){
        S= DS[--n];
        A= (S.rules)? S.rules: S.cssRules;
        for(var i= 0, L= A.length; i<L; i++){
            tem= A[i].selectorText? [A[i].selectorText, A[i].style.cssText]: [A[i]+''];
            if(s.test(tem[0])) SA[SA.length]= tem;
        }
    }
    return SA.join('\n\n');
}

getDefinedCss('p')//substitute a classname or id if you like

the latest item in the cascade is listed first.

like image 43
kennebec Avatar answered Oct 05 '22 16:10

kennebec


Add this Condition Above

if (!document.getElementsByClassName('className').length){
    //class not there
}
else{
//class there
}

If want to check on a element Just use

element.hasClassName( className );

also you can use on a ID

document.getElementById("myDIV").classList.contains('className');

Good Luck !!!

like image 45
Ignatius Andrew Avatar answered Oct 05 '22 16:10

Ignatius Andrew


Building on Helen's answer, I came up with this:

//**************************************************************************
//** hasStyleRule
//**************************************************************************
/** Returns true if there is a style rule defined for a given selector.
 *  @param selector CSS selector (e.g. ".deleteIcon", "h2", "#mid")
 */
  var hasStyleRule = function(selector) {

      var hasRule = function(selector, rules){
          if (!rules) return false;
          for (var i=0; i<rules.length; i++) {
              var rule = rules[i];
              if (rule.selectorText){ 
                  var arr = rule.selectorText.split(',');
                  for (var j=0; j<arr.length; j++){
                      if (arr[j].indexOf(selector) !== -1){
                          var txt = trim(arr[j]);
                          if (txt===selector){
                              return true;
                          }
                          else{
                              var colIdx = txt.indexOf(":");
                              if (colIdx !== -1){
                                  txt = trim(txt.substring(0, colIdx));
                                  if (txt===selector){
                                      return true;
                                  }
                              }
                          }
                      }
                  }
              }
          }
          return false;
      };

      var trim = function(str){
          return str.replace(/^\s*/, "").replace(/\s*$/, "");
      };

      for (var i=0; i<document.styleSheets.length; i++){
          var rules = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
          if (hasRule(selector, rules)){
              return true;
          }

          var imports = document.styleSheets[i].imports;
          if (imports){
              for (var j=0; j<imports.length; j++){
                  rules = imports[j].rules || imports[j].cssRules;
                  if (hasRule(selector, rules)) return true;
              }
          }
      } 

      return false;
  };
like image 40
Peter Avatar answered Oct 05 '22 17:10

Peter