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?
This question is related to
jquery
jquery-selectors
find
operators
JQuery uses CSS selectors to select elements, so you just need to use more than one rule by separating them with commas, as so:
a=$('[myc="blue"], [myid="1"], [myid="3"]');
Edit:
Sorry, you wanted blue and 1 or 3. How about:
a=$('[myc="blue"][myid="1"], [myid="3"]');
Putting the two attribute selectors together gives you AND, using a comma gives you OR.
First find the condition that occurs in all situations, then filter the special conditions:
$('[myc="blue"]')
.filter('[myid="1"],[myid="3"]');
In your special case it would be
a=$('[myc="blue"][myid="1"],[myc="blue"][myid="3"]');
To properly select the elements using the logical operations that you've stated, you just need jQuery.filter()
for the AND
operation, not "special filter functions". You also need jQuery.add()
for the OR
operation.
var elements = $('[myc="blue"]').filter('[myid="1"').add('[myid="3"');
Alternatively, it is possible to accomplish using shorthand in a single selector, where jamming selectors together acts as an AND
and separating with a comma acts as an OR
:
var elements = $('[myc="blue"][myid="1"], [myid="3"]');
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');
});
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"]');
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.
Source: Stackoverflow.com