Ramon K.
Ramon K.

Reputation: 3502

CSS/JQuery selectors: Is there anyway to select classes in classes?

Let's suppose that we have the following markup:

<div class="t-shirt black blue">Example</div>
<div class="t-shirt white blue">Example</div>
<div class="sweater black blue">Example</div>
<div class="sweater black red">Example</div>
<div class="sweater white red">Example</div>
<div class="hat black blue">Example</div>
<div class="hat black red">Example</div>
<div class="hat white red">Example</div>

Is there anyway to select t-shirt OR sweater that are black AND blue with one selector? I mean, without using comma separated selectors.

For example, I DON'T want to do the following:

var wanted = $('.t-shirt.black.blue, .sweater.black.blue');

Is there anyway to do something similar to the following? (I know it doesn't work):

var wanted = $('(.t-shirt, .sweater).black.blue');

Thanks in advance.

Upvotes: 2

Views: 152

Answers (4)

Reza Abolfathi
Reza Abolfathi

Reputation: 3191

var selectionLevel1 = $(".t-shirt, .sweater").andSelf();
var finalSelection = $(".black", selectionLevel1);

Upvotes: 0

BoltClock
BoltClock

Reputation: 723448

No, there isn't. Neither in jQuery nor CSS.

Even if there were a functional pseudo-class for grouping parts of selectors (such as the upcoming :matches() in Selectors 4), you would still need to supply a comma-separated list of those classes anyway:

:matches(.t-shirt, .sweater).black.blue

Needless to say, the above selector doesn't work in any browser (yet). You could implement it yourself as a Sizzle extension if you really wanted to, but I honestly wouldn't bother.

Upvotes: 6

Kevin B
Kevin B

Reputation: 95030

If the only goal is not using the comma, you could do this:

var blackblue = $(".black.blue"),
    tshirts = blackblue.filter(".t-shirt"),
    sweaters = blackblue.filter(".sweater"),
    both = tshirts.add(sweaters);

however i don't see how it is any better, unless it allows you to organize better.

Upvotes: 0

BinaryAnnie
BinaryAnnie

Reputation: 65

You can do something like that:

var wanted = $('.black.blue').filter('.t-shirt, .sweater');

But

var wanted = $('.t-shirt.black.blue, .sweater.black.blue');

might be more effective anyway (I have not tested that though)

Upvotes: 2

Related Questions