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?
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!
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.
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.
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").
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"]');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With