1

I have grabbed some XML data using this piece of jQuery:

$.ajax({
    type: "POST",
    url: "siteList.xml",
    dataType: "xml",
    success: function(xml) {
        $(xml).find('wrapper').each(function(){
            $(this).find('site').each(function(){
                //check whether this is the last element...
            });
        });
    }
});

What I would like to do is: Check whether I am parsing the last site element from the XML I pulled in.

edit: I cannot (as far as I'm aware), do this:

$(this).find('site').each(function(){
    $(this).last(); //nope
    $(this).find('site').last(); //nope
});
Barrie Reader
  • 10,647
  • 11
  • 71
  • 139
  • possible duplicate of [jQuery: how do I check if an element is the last sibling?](http://stackoverflow.com/questions/2681581/jquery-how-do-i-check-if-an-element-is-the-last-sibling) – Felix Kling Mar 20 '12 at 15:45
  • Not a duplicate - this is about XML not Markup – Barrie Reader Mar 20 '12 at 15:47
  • So? DOM is DOM. Whether you built it from XML or HTML does not matter (at least for traversal). I mean, you are also using `.find` here. Why should it be different for other functions? – Felix Kling Mar 20 '12 at 15:48
  • 1
    @Neurofluxation: What does the "M" in XML stand for? –  Mar 20 '12 at 15:48
  • *I cannot (as far as I'm aware), do this*... right, because the way you use `.last` here does not make sense. `$(this).last()` will be the same as `$(this)` as only one element is selected (`this`). As long as `site`'s are not nested, `$(this).find('site')` will return an empty set. – Felix Kling Mar 20 '12 at 15:51
  • Well, you get the last element before the `each` loop: `var last = $(this).find('site').get(-1);` (same as `$(this).find('site').last().get(0)`) and then compare it inside the the callback against `this`. Maybe you like this duplicate better: [How to find whether Current TD is last TD in TR](http://stackoverflow.com/questions/6705399/how-to-find-whether-current-td-is-last-td-in-tr). – Felix Kling Mar 20 '12 at 15:56

2 Answers2

2

Just use something like this to get the last site:

$(this).find('site').last()

Hope it helps!

Reinaldo
  • 4,556
  • 3
  • 24
  • 24
1

Take a look at the ':last' selector or the .last() function. You could do a test to see if the current site is the same as the last one.

JohnnyK
  • 1,103
  • 6
  • 10