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!
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.
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.
$ 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.
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
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