Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery reverse each() with find()

I know this kind of question has been asked before, but the general solution of

$($("input").get().reverse()).each(function() { /* ... */ });

is not working for me. I have an xml document that contains a list of concerts that I'd like to display on a webpage. So, in JQuery:

$.ajax({
    type: "GET",
    url: "concerts.xml",
    dataType: "xml",
    cache: false,
    success: function(xml) {
        $(xml).find('concert').each(function() {
            /*do stuff*/
        });
    }
});

However, I'd like to display the concerts in reverse order. So, I tried the following, but it did not work:

$.ajax({
    type: "GET",
    url: "concerts.xml",
    dataType: "xml",
    cache: false,
    success: function(xml) {
        $($(xml).find('concert').reverse()).each(function() {
            /*do stuff*/
        });
    }
});

Any assistance would be much appreciated. Thanks.

like image 247
ethan.roday Avatar asked Oct 21 '11 00:10

ethan.roday


2 Answers

You excluded the call to the get()[docs] method.

   // --------------------v
$($(xml).find('concert').get().reverse()).each(function() {

This is needed to get an Array of the elements from the jQuery object. This is what allows you to call .reverse(), which is on Array.prototype.

like image 87
user113716 Avatar answered Nov 12 '22 22:11

user113716


To walk through the items in reverse order, why not just use code like this:

var data = $("input");
for (var i = data.length - 1; i >= 0; i--) {
    var item = data[i];
    // do whatever you want to do with item here
}

Or, if you want to make a function out of it that takes a jQuery object and your function:

function reverseEach(jQueryObj, fn) {
    for (var i = jQueryObj.length - 1; i >= 0; i--) {
        if (fn.call(jQueryObj[i], i, jQueryObj[i]) === false) {
            break;
        }
    }
}

So, you could then call:

reverseEach($(xml).find('concert'), function() {
    // do stuff here
});

or:

reverseEach($("input"), function() {
    // do stuff here
});

Or, you could even make reverseEach a jQuery plugin if you wanted.

like image 45
jfriend00 Avatar answered Nov 12 '22 23:11

jfriend00