1

New to jQuery, I have a script that returns data from an XML file. What I need is the index number of the element returned. I know I can retreve a single element with this

name = $("sitelist:eq(1)",data).text();

but in my script I need to know each element position for the displayed data. something like position = $(data,eq).value .Can anyone help please .

$(document).ready(function () {

    $.ajax({
        type: "GET",
        url: "sites.xml",
        dataType: "xml",
        success: displayXml
    });

    function displayXml(data) {
        $(data).find("course").each(function () {
            var name = $(this).find("sitelist").text();
            var line1 = $(this).find("address1").text();
        });
    }
}); // doc ready

1 Answer 1

3

I'm not sure which node you need the index for, but if it is the course that you're iterating over with .each() you can get the index of each iteration from .each()

 $(data).find("course").each(function( idx ) {
      alert( idx ); // will alert the index of the current "course"

      var name = $(this).find("sitelist").text();
      var line1 = $(this).find("address1").text();
 });

If there's some other situation, you could try using the .index() method to get the index of the node from among its siblings. It requires jQuery 1.4 or later.

As in:

var $sitelist = $(this).find("sitelist");
var index = $sitelist.index();
var name = $sitelist.text();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.