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?
JQuery uses CSS selectors to select elements, so you just need to use more than one rule by separating them with commas, as so:
Edit:
Sorry, you wanted blue and 1 or 3. How about:
Putting the two attribute selectors together gives you AND, using a comma gives you OR.
AND operation
OR operation, use commas
As @Vega commented:
In your special case it would be
Simple use
.filter()
[docs] (AND) using the multiple selector [docs] (OR):In general, chaining selectors, like
a.foo.bar[attr=value]
is some kind of AND selector.jQuery has extensive documentation about the supported selectors, it's worth a read.
How about writing a filter like below,
Edit: @Jack Thanks.. totally missed it..
DEMO
The and operator in a selector is just an empty string, and the or operator is the comma.
There is however no grouping or priority, so you have to repeat one of the conditions: