jquery how to access the an xml node by index?
- by DS
Hi,
say I've an xml returned from server like this:
<persons>
<person>
<firstname>Jon</firstname>
</person>
<person>
<firstname>Jack</firstname>
</person>
<person>
<firstname>James</firstname>
</person>
</persons>
If I want to access the 3rd firstname node (passed dynamically and stored in i, assumed to be 3 here), how do I do that? My weird attempt follows:
var i=3;
$(xml).find('firstname').each(function(idx){
if (idx==i) alert($(this).text());
});
It does fetch me the right content... but it just feels wrong to me especially the looping part. Basically I'm looping through the whole tree using .each()! Is there any better approach than this? Something that'd take me to the nth node directly like:
alert( $(xml).find('firstname')[idx].text() ); // where idx=n
I'm new to jquery so please excuse my jquery coding approach.