Подтвердить что ты не робот

Как вы можете определить, существует ли класс css с Javascript?

Есть ли способ определить, существует ли класс css с использованием JavaScript?

4b9b3361

Ответ 1

Это можно сделать с использованием свойств document.styleSheets[].rules[].selectorText и document.styleSheets[].imports[].rules[].selectorText. Обратитесь к документации MDN.

Ответ 2

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

Ответ 3

/* Вы можете прокручивать каждую загруженную таблицу стилей и возвращать массив всех определенных правил для любого текста селектора, который вы указываете, от имен тегов до имен классов или идентификаторов.

Не включайте '#' или '.' префикс для имени id или класса.

Safari используется для пропуска запрещенных таблиц стилей, и там могут быть другие gotchas, но чтение правил обычно лучше работает в браузерах, чем написание новых. */

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, если вам нравится

последний элемент в каскаде указан сначала.

Ответ 4

Вот мое решение. Я по сути просто перебираю 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 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;
}

Эта функция обеспечивает улучшение скорости по сравнению с другими решениями, поскольку мы только просматриваем таблицу стилей, переданную функции. Другие решения проходят через все таблицы стилей, которые во многих случаях не нужны.

Ответ 5

Добавьте это условие выше

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

Если вы хотите проверить элемент Просто используйте

element.hasClassName( className );

также вы можете использовать на ID

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

Удачи!!!

Ответ 6

Вы можете проверить, есть ли объект стиля, который вы ищете, уже существует. Если это так, то класс 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 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;
    }

Обратите внимание, что это НЕ хороший подход, если вы ищете стиль, который не обязательно используется в вашем документе.

Ответ 7

Основываясь на ответах Хелен, я придумал это:

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