【问题标题】:Check if an element has no class specified [duplicate]检查元素是否没有指定类[重复]
【发布时间】:2016-05-12 14:13:36
【问题描述】:

我想检查一个元素是否指定了一个类(不知道类)。例如,给定:

<div id="ball" class="dd">

和:

<div id="ball">

我想检查它是否根本没有类。

我知道有一个名为 hasClass 的函数,但这需要类名才能工作。

编辑

该问题已在其他帖子中得到解答。 我发现最有用的答案是:

$("#mydiv").prop('classList').length

【问题讨论】:

    标签: jquery class exists


    【解决方案1】:

    如果你想检查元素是否有任何类,你可以使用.attr() 属性检查:

    $(element).attr("class").trim().length == 0
    

    这也处理这样的情况:

    <div class=""></div>
    

    您也可以尝试通过这种方式创建hasAttr() 函数:

    var attr = $(this).attr('name');
    
    // For some browsers, `attr` is undefined; for others, `attr` is false. Check for both.
    if (typeof attr !== typeof undefined && attr !== false) {
      // Element has this attribute
    }
    

    有关在A jQuery hasAttr() Equivalent 创建.hasAttr() 的更多信息。

    【讨论】:

    • 我试过 $(element).attr("class").trim().length==0 但不断收到错误 TypeError: S()attrr is undefined。因此,如果您根本没有课程,那是行不通的。
    • @ThomasWilliams 你看到第二个有hasAttr() 之类的东西了吗?您需要使用typeof 代码来检查undefined。试试看。
    【解决方案2】:

    一种可能的方法(如果您将具有空类的元素 - 例如 &lt;div class=""&gt;&lt;/div&gt; - 视为有类元素):

    $('#ball').is('[class]');
    

    比检查类属性值更直接。事实上,你甚至不需要 jQuery 来做到这一点:

    document.getElementById('ball').hasAttribute('class');
    

    另一个选项是使用classListThis API is tremendously useful(但 IE9- 不支持)。 classList 返回DOMTokenList,一个类似数组的对象;关键是,如果类属性没有设置或者为空,那么它的长度就是0:

    document.getElementById('ball').classList.length === 0;
    

    【讨论】:

    • 我相信&lt;div class=""&gt; 可能会失败,不是吗?
    • @PraveenKumar 你是对的,前段时间犯了同样的错误:)
    • 它为这样的元素显示true,但我认为这是OP的意图。如果不是,是的,最好将类值与空字符串进行比较,如您的答案所示。
    【解决方案3】:

    试试这个:

    <div id="ball" class="dd">
    <div id="ball">
    
    if ($('div').attr('class') != undefined){
            alert('YES');
        }
    

    【讨论】:

      【解决方案4】:

      试试这个

      var attr = $(this).attr('class');
      if (typeof attr !== typeof undefined && attr !== false) {
      
      }
      

      【讨论】:

      猜你喜欢
      • 2016-06-07
      • 2017-12-19
      • 1970-01-01
      • 2011-12-12
      • 2012-08-10
      • 1970-01-01
      • 1970-01-01
      • 2011-06-15
      相关资源
      最近更新 更多