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');
Related videos on Youtube
Comments
-
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 about 13 yearsAnd what if there was a
<div class="fuu yes">
? It doesn't have theno
class, but it would return false for.attr('class') == 'fuu'
. -
BoltClock about 13 yearsA 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 toquerySelectorAll()
instead of relying on Sizzle for those browsers, thereby improving performance on those browsers. Not that anyone cares, of course :) -
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 over 8 yearsI couldn't get following to work:
$("#mydiv .fuu:not(.no)").click(function(){console.log('test');});
. I searched a long time for a problem related tonot()
, finally it was simply because theactive
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, thinkingnot()
was not working, I thought a comment here might help others. -
Kip almost 6 yearsif you need to exclude multiple classes, the syntax is like:
$('.aaa:not(.bbb):not(.ccc)')
. That will get everything that has classaaa
but not classbbb
orccc