mike
mike

Reputation: 23811

Select items with one class and not other class jquery javascript

I want to select all items which are in one class and NOT in a set of other classes. For the first step, I imagined something like this would work, but didn't:

$('.class1,!.class2')

What I actually have is a list of classes that I don't want to select:

dont_select = ['class2', 'class3', 'class4']

And I want to select all items which have class1 but not any class in my array of classes in dont_select (which varies in length). Thanks,

Upvotes: 2

Views: 4451

Answers (4)

user2264882
user2264882

Reputation:

Your simple selector will be as below with Jquery

$('div.class1').not('.class2,.class3');

in the .not function of jquery you can put as much element as you want after ","

or if you have array then you can also go with the suggestion of Vega

dont_select = ['.class2', '.class3', '.class4']
$(selector).not(dont_select.join())

Go Ahead !!!

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

You should use .not function. See below,

dont_select = ['.class2', '.class3', '.class4']
$(selector).not(dont_select.join())

Note: Added a . to the string in dont_select array

Upvotes: 0

qwertymk
qwertymk

Reputation: 35274

Try this:

$(".class1").not("." + dont_select.join(",.") );

Upvotes: 6

Mike Robinson
Mike Robinson

Reputation: 25159

Give this a shot:

$(".class1:not(.class2)")

$(".class1:not(" + dont_select.join() + ")");

Upvotes: 1

Related Questions