[javascript] JQuery .each() backwards

I'm using JQuery to select some elements on a page and then move them around in the DOM. The problem I'm having is I need to select all the elements in the reverse order that JQuery naturally wants to select them. For example:

<ul>
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
   <li>Item 4</li>
   <li>Item 5</li>
</ul>

I want to select all the li items and use the .each() command on them but I want to start with Item 5, then Item 4 etc. Is this possible?

This question is related to javascript jquery arrays reverse

The answer is


You cannot iterate backwards with the jQuery each function, but you can still leverage jQuery syntax.

Try the following:

//get an array of the matching DOM elements   
var liItems = $("ul#myUL li").get();

//iterate through this array in reverse order    
for(var i = liItems.length - 1; i >= 0; --i)
{
  //do Something
}

I present you with the cleanest way ever, in the form of the world's smallest jquery plugin:

jQuery.fn.reverse = [].reverse;

Usage:

$('jquery-selectors-go-here').reverse().each(function () {
    //business as usual goes here
});

-All credit to Michael Geary in his post here: http://www.mail-archive.com/[email protected]/msg04261.html


Here are different options for this:

First: without jQuery:

var lis = document.querySelectorAll('ul > li');
var contents = [].map.call(lis, function (li) {
    return li.innerHTML;
}).reverse().forEach(function (content, i) {
    lis[i].innerHTML = content;
});

Demo here

... and with jQuery:

You can use this:

$($("ul > li").get().reverse()).each(function (i) {
    $(this).text( 'Item ' + (++i));
});

Demo here

Another way, using also jQuery with reverse is:

$.fn.reverse = [].reverse;
$("ul > li").reverse().each(function (i) {
    $(this).text( 'Item ' + (++i));
});

This demo here.

One more alternative is to use the length (count of elements matching that selector) and go down from there using the index of each iteration. Then you can use this:

var $li = $("ul > li");
$li.each(function (i) {
    $(this).text( 'Item ' + ($li.length - i));
});

This demo here

One more, kind of related to the one above:

var $li = $("ul > li");
$li.text(function (i) {
    return 'Item ' + ($li.length - i);
});

Demo here


I think u need

.parentsUntill()

If you don't want to save method into jQuery.fn you can use

[].reverse.call($('li'));

I prefer creating a reverse plug-in eg

jQuery.fn.reverse = function(fn) {       
   var i = this.length;

   while(i--) {
       fn.call(this[i], i, this[i])
   }
};

Usage eg:

$('#product-panel > div').reverse(function(i, e) {
    alert(i);
    alert(e);
});

I found Array.prototype.reverse unsuccessful with objects, so I made a new jQuery function to use as an alternative: jQuery.eachBack(). It iterates through as the normal jQuery.each() would, and stores each key into an array. It then reverses that array and performs the callback on the original array/object in the order of the reversed keys.

jQuery.eachBack=function (obj, callback) {
    var revKeys=[]; $.each(obj,function(rind,rval){revKeys.push(rind);}); 
    revKeys.reverse();
    $.each(revKeys,function (kind,i){
        if(callback.call(obj[i], i, obj[i]) === false) {    return false;}
    });
    return obj;
}   
jQuery.fn.eachBack=function (callback,args) {
    return jQuery.eachBack(this, callback, args);
}

You can do

jQuery.fn.reverse = function() {
    return this.pushStack(this.get().reverse(), arguments);
}; 

followed by

$(selector).reverse().each(...) 

Needed to do a reverse on $.each so i used Vinay idea:

//jQuery.each(collection, callback) =>
$.each($(collection).get().reverse(), callback func() {});

worked nicely, thanks


You can also try

var arr = [].reverse.call($('li'))
arr.each(function(){ ... })

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to reverse

Right way to reverse a pandas DataFrame? Reverse Contents in Array Reverse a string without using reversed() or [::-1]? angular ng-repeat in reverse Reversing an Array in Java Reversing a String with Recursion in Java Print a list in reverse order with range()? How to reverse an std::string? Python list sort in descending order How to get a reversed list view on a list in Java?