Wrapcode

Iterate each element in reverse order using JQuery

| 2 min read

Iterate each element in reverse order using JQuery

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--){
$('li').eq(i).someSuperLogicHere;
}
view raw each.js hosted with ❤ by GitHub

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://www.mail-archive.com/discuss@jquery.com/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() {
// YOUR SUPER LOGIC HER
} );
view raw reverse.js hosted with ❤ by GitHub

Simple, isn't it?