I thought of another way to implement this by treating it as a kind of stack. Example in jsFiddle .
Stack
Firstly I need to save the elements in a variable.
var elements = $("li");
In this way elements are sorted as 1
, 2
, 3
, 4
, 5
. My "stack" looks like this:
5 <- last in (último a entrar)
---------
4
---------
3
---------
2
---------
1 <- first in (primeiro a entrar)
Splice
jQuery does not have a pop
method, but you can copy the same behavior using:
elements.splice( ultimo_indice, 1);
That is, I get the values of the "stack", since 5
was the last one to enter, it will be the first one to exit.
So I do:
// enquanto houver elementos na pilha, remove e
var e;
while ((e = elements.splice(elements.length - 1, 1)).length)
{
// re-adiciona o próprio elemento no seu container
$("ul").append(e[0]);
}
I'm drawing in order 5
, 4
, 3
, 2
, 1
and re-inserting them, thus changing the order of elements.
Pop
It is possible to implement the pop
method to be used directly on a jQuery object, so add the method as follows:
!function($) {
$.fn.pop = function() { return this.splice(this.length - 1, 1)[0]; }
}(jQuery);
And to use in this example:
var elements = $("li");
var e;
while ((e = elements.pop()))
{
$("ul").append(e);
}
Example in jsFiddle
Direct method
And a simpler method, but one that is very efficient is to go through the elements in reverse order by re-adding them:
var elements = $("li");
for (var i = elements.length - 1; i >= 0; --i)
{
$("ul").append(elements[i]);
}
Performance
And to complete a performance test: Reversing order of jsPerf elements
Nome op/s
--------------------------------------------
ModoSplice 7,582
ModoPop 7,340
ModoDireto 8,357
ModoReverse /* [].reverse.call */ 11,679 <--