jquery how to access the an xml node by index?

Posted by DS on Stack Overflow See other posts from Stack Overflow or by DS
Published on 2010-05-21T05:15:34Z Indexed on 2010/05/21 5:20 UTC
Read the original article Hit count: 200

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about Xml