如何确定jss是否存在css类?

时间:2009-06-11 20:50:53

标签: javascript

有没有办法确定使用JavaScript是否存在css类?

11 个答案:

答案 0 :(得分:30)

这应该可以使用document.styleSheets[].rules[].selectorTextdocument.styleSheets[].imports[].rules[].selectorText属性。请参阅MDN documentation

答案 1 :(得分:12)

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;
}

答案 2 :(得分:4)

/ * 您可以遍历当前加载的每个样式表,并为您指定的任何选择器文本返回所有已定义规则的数组,从标记名称到类名称或标识符。

不要包含'#'或'。' id或类名的前缀。

Safari用于跳过已禁用的样式表,并且可能还有其他问题,但阅读规则通常在浏览器中比编写新规则更好。 * /

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') //如果您愿意,可以替换类名或ID

级联中的最新项目列在第一个

答案 3 :(得分:3)

以下是我的解决方案。我基本上只是循环遍历document.styleSheets []。rules []。selectorText @helen建议。

/**
 * 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;
}

与其他解决方案相比,此功能提供了速度提升,因为我们只搜索传递给函数的样式表。其他解决方案遍历所有样式表,这在许多情况下是不必要的。

答案 4 :(得分:2)

基于answer,我创建了一个javascript函数,用于在浏览器的内存中搜索CSS类-

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');

这将在任何样式表中的任何规则中为每次出现的类名打印一行。

Ref-Search for a CSS class in the browser memory

答案 5 :(得分:1)

根据海伦的回答,我想出了这个:

//**************************************************************************
//** 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;
  };

答案 6 :(得分:0)

将此条件添加到上方

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

如果想要检查元素,请使用

element.hasClassName( className );

您也可以使用ID

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

祝你好运!!!

答案 7 :(得分:0)

可以检查并查看您正在寻找的样式对象是否已存在。如果是,则css类必须存在,因为对象正在使用它。例如,如果您想确保明确命名的svg对象各自具有自己的样式:

function getClassName(name) {
    //Are there any elements which use a style named 'name' ?
    if (document.getElementsByClassName(name).length === 0){
        //There are none yest, let's make a new style and add it
        var style = document.createElement('style');
        style.type = 'text/css';
        //Where you might provide your own hash function or rnd color
        style.innerHTML = '.'+name+' { fill: #' + getHashColor(name) + '; background: #F495A3; }';
        //Add the style to the document
        document.getElementsByTagName('head')[0].appendChild(style);
        }
        return name;
    }

请注意,如果您正在寻找不一定在文档中使用的样式,这是 NOT 一个好方法。

答案 8 :(得分:0)

if ($(".class-name").length > 0) {

}

这是使用javascript检查HTML中的类的好方法

答案 9 :(得分:0)

Oneliner:

[].slice.call(document.styleSheets)
.reduce( (prev, styleSheet) => [].slice.call(styleSheet.cssRules))
.reduce( (prev, cssRule) => prev + cssRule.cssText)
.includes(".someClass")

答案 10 :(得分:0)

function getAllSelectors() {
  var ret = {};
  for(var i=0;i<document.styleSheets.length;i++){
    try {
      var rules = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
      for(var x in rules) {
        if(typeof rules[x].selectorText === 'string'){
          if(ret[rules[x].selectorText] === undefined){
            ret[rules[x].selectorText] = rules[x].style.cssText;
          }
          else {
            ret[rules[x].selectorText] = ret[rules[x].selectorText] + ' ' + rules[x].style.cssText;
          }
        }
      }    
    }
    catch(error){
      console.log(document.styleSheets[i]);
    }
  }
  return ret;
}
function selectorExists(selector) {
  var selectors = getAllSelectors();
  if(selectors[selector] !== undefined){
    return true;
  }
  return false;
}
// var allSelectors = getAllSelectors();