jQuery select by attribute using AND and OR operators
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?
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"]');
Simple use .filter()
[docs] (AND) using the multiple selector [docs] (OR):
$('[myc="blue"]').filter('[myid="1"],[myid="2"]');
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,
$('[myc="blue"]').filter(function () {
return (this.id == '1' || this.id == '3');
});
Edit: @Jack Thanks.. totally missed it..
$('[myc="blue"]').filter(function() {
var myId = $(this).attr('myid');
return (myId == '1' || myId == '3');
});
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:
a=$('[myc=blue][myid="1"],[myc=blue][myid="3"]');
First find the condition that occurs in all situations, then filter the special conditions:
$('[myc="blue"]')
.filter('[myid="1"],[myid="3"]');