How to check if an element does NOT have a specifi

2019-01-16 01:58发布

问题:

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")){
}

回答1:

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


回答2:

sdleihssirhc's answer is of course the correct one for the case in the question, but just as a reference if you need to select elements that don't have a certain class, you can use the not selector:

// select all divs that don't have class test
$( 'div' ).not( ".test" );
$( 'div:not(.test)' );  // <-- alternative 


回答3:

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).



回答4:

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

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

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



回答5:

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


回答6:

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



回答7:

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