In jQuery I’m trying to select only mount nodes where a and b’s text values are 64 and “test” accordingly. I’d also like to fallback to 32 if no 64 and “test” exist. What I’m seeing with the code below though, is that the 32 mount is being returned instead of the 64.
The XML:
<thingses>
<thing>
<a>32</a> <-- note, a here is 32 and not 64 -->
<other>...</other>
<mount>sample 1</mount>
<b>test</b>
</thing>
<thing>
<a>64</a>
<other>...</other>
<mount>sample 2</mount>
<b>test</b>
</thing>
<thing>
<a>64</a>
<other>...</other>
<mount>sample 3</mount>
<b>unrelated</b>
</thing>
<thing>
<a>128</a>
<other>...</other>
<mount>sample 4</mount>
<b>unrelated</b>
</thing>
</thingses>
And unfortunately I don’t have control over the XML as it comes from somewhere else.
What I’m doing now is:
var ret_val = '';
$data.find('thingses thing').each(function(i, node) {
var $node = $(node), found_node = $node.find('b:first:is(test), a:first:is(64)').end().find('mount:first').text();
if(found_node) {
ret_val = found_node;
return;
}
found_node = $node.find('b:first:is(test), a:first:is(32)').end().find('mount:first').text();
if(found_node) {
ret_val = found_node;
return;
}
ret_val = 'not found';
});
// expected result is "sample 2", but if sample 2's parent "thing" was missing, the result would be "sample 1"
alert(ret_val);
For my “:is” selector I’m using:
if(jQuery){
jQuery.expr[":"].is = function(obj, index, meta, stack){
return (obj.textContent || obj.innerText || $(obj).text() || "").toLowerCase() == meta[3].toLowerCase();
};
}
There has to be a better way than how I’m doing it. I wish I could replace the “,” with “AND” or something. 🙂
Any help would be much appreciated. thanks!
Why do you call
end()afterfind()? I may not understand your intention correctly, butend()takes you back to$node, so that the subsequentfind("mount:first")just returns you the firstmountchild of that.Am I wrong here?
Edit
Besides, why do you do
.eachon allthings? This way, yourret_valuewill actually get themountvalue of the lastthingthat conforms to the 64-if-not-then-32 condition.If you want to select the first 64/test
thing, and if there no such thing, then the first 32/test, then why don’t you just write this explicitly?And you could encapsulate that long query to make the code more readable:
Do I misunderstand what you need? Because I’m a bit confused 🙂