jQuery select a div with a certain class, that doesn't have another class

31,424

Solution 1

Use :not() to exclude the other class:

$('.fuu:not(.no)')

Solution 2

You can also filter out the '.no' class with something like:

$('.fuu').not('.no');
Share:
31,424

Related videos on Youtube

Alex
Author by

Alex

I'm still learning so I'm only here to ask questions :P

Updated on July 05, 2022

Comments

  • Alex
    Alex almost 2 years
    <div class="fuu">
      ...
    </div>
    
    <div class="fuu no">
      ...
    </div>
    
    ...
    

    How can I select all fuu's besides the ones that have the .no class?

  • BoltClock
    BoltClock about 13 years
    And what if there was a <div class="fuu yes">? It doesn't have the no class, but it would return false for .attr('class') == 'fuu'.
  • BoltClock
    BoltClock about 13 years
    A little tidbit: .fuu:not(.no) is also a valid CSS3 selector, and will match the same elements on browsers that support :not(). Thus I believe jQuery will hand this selector to querySelectorAll() instead of relying on Sizzle for those browsers, thereby improving performance on those browsers. Not that anyone cares, of course :)
  • Mario Awad
    Mario Awad over 10 years
    +1 from me on the nice extra tip, and with a +8 so far it seems that "some" developers do care about performance :-)
  • fpierrat
    fpierrat over 8 years
    I couldn't get following to work: $("#mydiv .fuu:not(.no)").click(function(){console.log('test');}); . I searched a long time for a problem related to not(), finally it was simply because the active class was added dynamically. I had to do it like this: $("#mydiv").on('click', '.fuu:not(.no)', function(){console.log('test');}); . Since I kept digging 'round here, thinking not() was not working, I thought a comment here might help others.
  • Kip
    Kip almost 6 years
    if you need to exclude multiple classes, the syntax is like: $('.aaa:not(.bbb):not(.ccc)'). That will get everything that has class aaa but not class bbb or ccc