[jquery] 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?

This question is related to jquery jquery-selectors find operators

The answer is


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');
});

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"]');

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.


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-selectors

Why is my JQuery selector returning a n.fn.init[0], and what is it? How to use placeholder as default value in select2 framework Access the css ":after" selector with jQuery jQuery: using a variable as a selector Check if any ancestor has a class using jQuery jQuery selector first td of each row Select element by exact match of its content jQuery selector to get form by name jQuery : select all element with custom attribute Set select option 'selected', by value

Examples related to find

Find a file by name in Visual Studio Code Explaining the 'find -mtime' command find files by extension, *.html under a folder in nodejs MongoDB Show all contents from all collections How can I find a file/directory that could be anywhere on linux command line? Get all files modified in last 30 days in a directory FileNotFoundError: [Errno 2] No such file or directory Linux find and grep command together find . -type f -exec chmod 644 {} ; Find all stored procedures that reference a specific column in some table

Examples related to operators

What is the difference between i = i + 1 and i += 1 in a 'for' loop? Using OR operator in a jquery if statement What is <=> (the 'Spaceship' Operator) in PHP 7? What does question mark and dot operator ?. mean in C# 6.0? Boolean operators ( &&, -a, ||, -o ) in Bash PowerShell and the -contains operator How do I print the percent sign(%) in c Using the && operator in an if statement What do these operators mean (** , ^ , %, //)? How to check if div element is empty