Iterate each element in reverse order using JQuery


Being a web developer, everyone find JQuery a life savior. For the past two months, I am working on some heavy JavaScript work. Thanks to JQuery for helping me a lot with unbelievably simple to use api.  But there are some situations where you will have to depend on your own code instead of using ‘the beautiful JQuery library’.

JQuery, the coolest thing since sliced bread!

I was struggling with some responsive menu bar stuff. We had to make it responsive in a very creative manner (not like bootstrap responsive navigation bar). There I needed to iterate each element of list in reverse manner. As usual, I googled for any ready api available in JQuery but unfortunately there was not any good and short method available. I could have easily achieved reverse iteration using

for( i =  $('li').size(); i>= 0 ; i--){

But somehow this was not the best possible solution to iterate and add logic. After looking for appropriate solution online, I stumbled upon this archive : http:[email protected]/msg04261.html which guided me to get it done by creating one line plugin for JQuery.

Why not create world’s smallest JQuery plugin?

Yes, there is no .reverse() i.e. reverse iteration in JQuery. What if we don’t have. We can create our own plugin. No worries, it is not lengthy. Just a one liner, I promise. Just add this in your Js file.

jQuery.fn.reverse = [].reverse;

Well, that’s it.

How does it work?

Anyone with moderate JQuery and JavaScript knowledge can explain working of the above prototype. It takes elements in to array and reverse it using JavaScript reverse.

World’s smallest plugin in action!

Usage is simple, if you are using .each iterator just add .reverse() before .each iterator function.

$('li').reverse().each( function() {
} );

Simple, isn’t it?

  • Thanks for so ideal idea! You are awesome. I tried to do this using parse of elements and for loop before my each & this take 10 lines of my code & when I now see this new way – I think “Wau!!!”

    • Glad it helped mate!