tags:

views:

102

answers:

2

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.

A: 

.eq()


Categories: Traversing > Filtering

.eq( index )

Returns: jQuery

Description: Reduce the set of matched elements to the one at the specified index.

version added: 1.1.2.

index
An integer indicating the 0-based position of the element.

http://api.jquery.com/eq/

Robert Harvey
I tried it right now and it worked. It's so much more elegant! I'm loving jQuery more and more everyday. Thank you for pointing me to the right resource.
DS
A: 

Here's where I reached finally. Let me know if you think it can be even better!

var i=3;
alert($(xml).find('firstname').eq(i).text());

Thank you, Robert!

DS