jQuery select by attribute using AND and OR operators

The Bndr picture The Bndr · May 21, 2012 · Viewed 164.2k times · Source

I'm thinking about, if it is possible in jQuery to select elements by named attributes using AND and OR.

Example:

<div myid="1" myc="blue">1</div>
<div myid="2" myc="blue">2</div>
<div myid="3" myc="blue">3</div>
<div myid="4">4</div>

I'd like to select all the elements where myc="blue" but only those with myid set to either 1 or 3.

So I tried:

a=$('[myc="blue"] [myid="1"]  [myid="3"]');

but it does not work, same here:

a=$('[myc="blue"] && [myid="1"] || [myid="3"]');

Is it possible without writing special filter functions?

Answer

Gabe picture Gabe · May 21, 2012

AND operation

a=$('[myc="blue"][myid="1"][myid="3"]');

OR operation, use commas

a=$('[myc="blue"],[myid="1"],[myid="3"]');

As @Vega commented:

a=$('[myc="blue"][myid="1"],[myc="blue"][myid="3"]');