Jquery how to access xml node by index?

Let's say I have xml returned from the server as follows:

<persons>
        <person>
               <firstname>Jon</firstname>
        </person>
        <person>
               <firstname>Jack</firstname>
        </person>
        <person>
               <firstname>James</firstname>
        </person>
</persons>

If I want to access the 3rd first name of the node (transferred dynamically and stored in i, it is assumed that 3 here), how to do it? My weird attempt:

var i=3;
$(xml).find('firstname').each(function(idx){
       if (idx==i) alert($(this).text());
});

It brings me the right content ... but it just feels awkward for me, especially for the cycle. I mostly loop around the whole tree using .each ()! Is there a better approach than this? Something that will lead me to an nth node is just like:

alert( $(xml).find('firstname')[idx].text() ); // where idx=n

I am new to jquery, so please excuse my approach to jquery encoding.

+3
source share
2 answers

.eq ()


Categories: Moving> Filtering

.eq (index)

Returns: jQuery

. , .

: 1.1.2.


, 0.

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

+4

, . , , !

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

, !

+1

Source: https://habr.com/ru/post/1746507/


All Articles