Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 392
The Bndr Avatar asked May 21 '12 14:05

The Bndr


People also ask

How do you select an element with specific attributes?

The [attribute^="value"] selector is used to select elements with the specified attribute, whose value starts with the specified value. The following example selects all elements with a class attribute value that starts with "top": Note: The value does not have to be a whole word!

What does ATTR do in jQuery?

jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.

How get multiple data attribute values in jQuery?

that's because when you call the data method on the jQuery object, it returns the data for the first element in the nodeList. To get the data for all the div's you have to loop through the elements with the $. each method or use a mapping to retrieve the attributes in a list.

What jQuery syntax selects HTML elements by a specific attribute and its value?

The [attribute|=value] selector selects each element with a specified attribute, with a value equal to a specified string (like "en") or starting with that string followed by a hyphen (like "en-us").


1 Answers

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"]'); 
like image 143
Gabe Avatar answered Sep 30 '22 10:09

Gabe