I thought of another way to implement this, treating as a kind of stack. Example in jsFiddle.
Stack
First I need to store the elements in a variable.
var elements = $("li");
In this way the elements are ordered 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 method pop
, but it is possible to copy the same behavior using:
elements.splice( ultimo_indice, 1);
That is, I get the values of the "stack", since 5
was the last to enter, he will be the first to leave.
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 taking it in order 5
, 4
, 3
, 2
, 1
and re-insert them, thus changing the order of the elements.
Pop
It is possible to implement the method pop
to be used directly on a jQuery object, simply 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 more bland but very efficient method 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 <--
I would suggest, for the sake of ease of search and greater cohesion with what is being discussed, that the title of this question be changed to "Reverse the order of the elements of a list using jQuery". Of course, it’s just a suggestion.
– FReNeTiC
@Frenetic, I agree that can be clearer, thank you. I have made a modification now to be clearer.
– Sergio