How to check if an element does NOT have a specifi

2019-01-16 01:25发布

How do I check if there isn't a class. For example, I know how to check to see if it has the class "test", but how do I check to see if it doesn't have the class "test"?

if($(this).hasClass("test")){
}

7条回答
闹够了就滚
2楼-- · 2019-01-16 01:59

use the .not() method and check for an attribute:

$('p').not('[class]');

Check it here: http://jsfiddle.net/AWb79/

查看更多
放我归山
3楼-- · 2019-01-16 02:01

Select element (or group of elements) having class "abc", not having class "xyz":

    $('.abc:not(".xyz")')

When selecting regular CSS you can use .abc:not(.xyz).

查看更多
Bombasti
4楼-- · 2019-01-16 02:02
if (!$(this).hasClass("test")) {
查看更多
霸刀☆藐视天下
5楼-- · 2019-01-16 02:04

There are more complex scenarios where this doesn't work. What if you want to select an element with class A that doesn't contain elements with class B. You end up needing something more like:

If parent element does not contain certain child element; jQuery

查看更多
我只想做你的唯一
6楼-- · 2019-01-16 02:08

reading through this 6yrs later and thought I'd also take a hack at it, also in the TIMTOWTDI vein...:D, hoping it isn't incorrect 'JS etiquette'.

I usually set up a var with the condition and then refer to it later on..i.e;

// var set up globally OR locally depending on your requirements
var hC;

function(el) {
  var $this = el;
  hC = $this.hasClass("test");

  // use the variable in the conditional statement
  if (!hC) {
    //
  }
}

Although I should mention that I do this because I mainly use the conditional ternary operator and want clean code. So in this case, all i'd have is this:

hC ? '' : foo(x, n) ;
   // OR -----------
!hC ? foo(x, n) : '' ;

...instead of this:

$this.hasClass("test") ? '' : foo(x, n) ;
   // OR -----------
(!$this.hasClass("test")) ? foo(x, n) : '' ;
查看更多
别忘想泡老子
7楼-- · 2019-01-16 02:09

You can try this:

<div id="div1" class="myClass">there is a class</div>
<div id="div2"> there is no class2 </div>

$(document).ready(function(){
    $("#div2").not('.myClass');  // do not have `myClass` class.
});
查看更多
登录 后发表回答