Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I combine logical OR with logical AND within a jQuery attribute selector?

Given the following XML:

<users>
    <user state="CA" sex="m">Max</user>
    <user state="AZ" sex="f">Jen</user>
    <user state="OR" sex="f">Kim</user>
    <user state="NV" sex="m">Bob</user>
    <user state="CA" sex="m">Jon</user>
    <user state="AZ" sex="m">Jim</user>
    <user state="OR" sex="f">Joy</user>
    <user state="NV" sex="f">Amy</user>
</users>

Using jQuery, is there a way to select users who are male and are either from CA or NV, but without using the filter function? To be clear, I know that

$(xml).find("user[sex='m']")

selects only male users, while

$(xml).find("user[state='CA'],[state='NV']")

selects all users from either CA or NV. But I am not able to combine both of them with a logical AND within a single selector.

Using the filter function, however, the following works:

$(xml).find("user").filter(function() {
    return $(this).attr('sex') == 'm' && ($(this).attr('state') == 'CA' || $(this).attr('state') == 'NV')
}).each(function() {
    alert($(this).text());
});

Thanks!

like image 408
user537264 Avatar asked Dec 10 '10 01:12

user537264


People also ask

What is the correct way of selecting the current element with jQuery selectors?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

Which is the correct jQuery selector to select all elements within the div?

Tag Class: It represents a tag available with a specific class in the DOM. For example: $('real-class') selects all elements in the document that have a class of real-class.

What is $$ in jQuery?

$ is another, which is just an alias to jQuery . $$ is not provided by jQuery. It's provided by other libraries, such as Mootools or Prototype. js. More importantly, $$ is also provided in the console of modern browsers as an alias to document.


1 Answers

Try this:

$(xml).find("user[sex='m'][state='CA'], user[sex='m'][state='NV']")

Basically you chain the sex and state attributes together in a single simple selector (this would be your logical AND), and repeat them once per state (and this would be your logical OR).

Test:

$(xml).find("user[sex='m'][state='CA'], user[sex='m'][state='NV']")
      .each(function() {
          alert($(this).text() + " - " + $(this).attr('state'));
      });

Output:

Max - CA
Bob - NV
Jon - CA
like image 195
BoltClock Avatar answered Sep 25 '22 00:09

BoltClock