294
votes

Is there a simple selector expression to not select elements with a specific class?

<div class="first-foo" />
<div class="first-moo" />
<div class="first-koo" />
<div class="first-bar second-foo" />

I just want to get the first three divs and tried

$(div[class^="first-"][class!="first-bar"])

But this receives all as the last div contains more than first-bar. Is there a way to use a placeholder in such an expression? Something like that

$(div[class^="first-"][class!="first-bar*"]) // doesn't seem to work

Any other selectors that may help?

3
Scratch my earlier comment, I just reread the question. Critical class is first-bar. - BoltClock♦
In case one wants to select all elements that do not have either class1 or class2, concatenating would work: $('div[class^="first-"]').not('.class1').not('.class2') - J0ANMM

3 Answers

587
votes

You need the :not() selector:

$('div[class^="first-"]:not(.first-bar)')

or, alternatively, the .not() method:

$('div[class^="first-"]').not('.first-bar');
91
votes

You can use the :not filter selector:

$('foo:not(".someClass")')

Or not() method:

$('foo').not(".someClass")

More Info:

1
votes

You can write a jQuery selector in the "not" method:

$('div[class^="first-"]').not($('.first-bar'))