user834595
user834595

Reputation:

JQuery selecting class and one of a number of other classes

I've aware that you can select ".fred.barney" to find things with class 'fred' and 'barney' and that you can use '.fred,.barney' to find things with EITHER of those classes.

I have a slightly more complex need tho - I need to find items which have a specific class and then one of a number of other classes also.

Example

<span class="item fred">...
<span class="item barney">...
<span class="item dave">...

I need to find the spans which have class 'item' (so $(".item")) and which have also have either 'fred' or 'barney'

Only way I can thing-of atm is to use

$(".item").each(function() {
  if ($(this).is(".barney,.fred")) ...
})

Is there a way to do this within the selector to save the extra code tho?

Upvotes: 0

Views: 55

Answers (4)

jdehlin
jdehlin

Reputation: 11471

You could try:

$(".item.barney, .item.fred")

Upvotes: 0

Adil Shaikh
Adil Shaikh

Reputation: 44740

You can do this -

$('.item.fred,.item.barney')

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 122026

You need some thing like this

$('span.item.fred.barney');

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 817198

You can use a combination of both selectors:

$('.item.fred, .item.barney');

or use .filter:

$('.item').filter('.fred, .barney');

or vice versa

$('.fred, .barney').filter('.item');

If fred and barney only appear together with item anyway, just use

$('.fred, .barney')

Upvotes: 4

Related Questions