Not class selector in jQuery

JavascriptJqueryJquery Selectors

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

You need the :not() selector:

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

or, alternatively, the .not() method:

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

Solution 2 - Javascript

You can use the :not filter selector:

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

Or not() method:

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

More Info:

Solution 3 - Javascript

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZardozView Question on Stackoverflow
Solution 1 - JavascriptlonesomedayView Answer on Stackoverflow
Solution 2 - JavascriptSarfrazView Answer on Stackoverflow
Solution 3 - JavascriptNur.BView Answer on Stackoverflow