如何确定是否存在带有Javascript的css类?

如何确定是否存在带有Javascript的css类?,javascript,Javascript,有没有一种方法可以使用JavaScript确定css类是否存在?这应该可以通过使用文档.样式表[].规则[].选择文本和文档.样式表[].导入[].规则[].选择文本属性来实现。请参阅。/* 您可以在当前加载的每个样式表中循环,并为您指定的任何选择器文本返回一个包含所有已定义规则的数组,从标记名到类名或标识符 不要在id或类名中包含“#”或“.”前缀 Safari过去常常跳过禁用的样式表,可能还有其他问题,但在不同浏览器中阅读规则通常比编写新规则更有效。 */ 函数getDefinedCss(s

有没有一种方法可以使用JavaScript确定css类是否存在?

这应该可以通过使用
文档.样式表[].规则[].选择文本
文档.样式表[].导入[].规则[].选择文本
属性来实现。请参阅。

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

不要在id或类名中包含“#”或“.”前缀

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

函数getDefinedCss(s){ 如果(!document.styleSheets)返回“”; if(typeof s=='string')s=RegExp('\\b'+s+'\\b','i');//IE将html选择器大写 var A,S,DS=document.styleSheets,n=DS.length,SA=[]; while(n){ S=DS[--n]; A=(S.rules)?S.rules:S.cssRules; 对于(var i=0,L=A.length;i
函数getAllSelectors(){
var-ret=[];
for(var i=0;i
这是我的解决方案。我基本上只是在文档中循环。样式表[]。规则[]。按照@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;
}
/**
*此函数用于搜索给定样式表中是否存在指定的CSS选择器。
*
*@param(string)styleSheetName-这是您要搜索的样式表的名称
*@param(string)选择器-这是您要查找的选择器的名称
*@return(bool)-如果找到选择器,则返回true;如果未找到选择器,则返回false
*@example-console.log(selectornstylesheet('myStyleSheet.css','.myClass');
*/    
函数选择器样式表(样式表名称、选择器){
/*
*从document.styleSheets对象获取“styleSheetName”的索引
*/
for(var i=0;i

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

添加上述条件

if (!document.getElementsByClassName('className').length){
    //class not there
}
else{
//class there
}
如果要检查某个元素,只需使用

element.hasClassName( className );
也可以在ID上使用

document.getElementById("myDIV").classList.contains('className');
祝您好运!!!

您可以检查并查看您正在查找的样式的对象是否已经存在。如果已经存在,则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;
    }

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

基于Helen的答案,我提出了以下建议:

//**************************************************************************
//** 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;
  };
//**************************************************************************
//**哈斯泰勒规则
//**************************************************************************
/**如果为给定选择器定义了样式规则,则返回true。
*@param选择器CSS选择器(例如“.deleteIcon”、“h2”、“mid”)
*/
var hasStyleRule=函数(选择器){
var hasRule=函数(选择器、规则){
如果(!rules)返回false;
对于(var i=0;i
这是一种使用javascript检查HTML中类的好方法,Oneliner:

[].slice.call(document.styleSheets)
.reduce( (prev, styleSheet) => [].slice.call(styleSheet.cssRules))
.reduce( (prev, cssRule) => prev + cssRule.cssText)
.includes(".someClass")
基于,我创建了一个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');
var searchForCss=函数(searchClassName){
for(设i=0;i
这将为任何样式表中的任何规则中出现的每个类名打印一行

Ref-

函数getAllSelectors(){
var ret={};

对于(var i=0;i)类存在是什么意思?该类至少有一个元素,或者至少有一个CSS规则应用于该类的元素?对不起,我的意思是…存在吗
if ($(".class-name").length > 0) {

}
[].slice.call(document.styleSheets)
.reduce( (prev, styleSheet) => [].slice.call(styleSheet.cssRules))
.reduce( (prev, cssRule) => prev + cssRule.cssText)
.includes(".someClass")
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');
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();