1

I have a dynamic list that I am trying to switch the current order on. In this example it is 1,2,3 I am trying to make it 3,2,1

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>

If it was not dynamic i would use $('li:first').before('li:last') a couple times but the number of elements is always changing, is there a simple way to accomplish this?

user934902
  • 1,156
  • 3
  • 15
  • 33

3 Answers3

4

You might want to give ul an id, but this should work:

$('ul').append($('ul').find('li').get().reverse());

Fiddle

dezman
  • 16,081
  • 9
  • 51
  • 87
4

Another simple solution:

$('li').each(function() {
    $(this).parent().prepend(this);
});

DEMO: http://jsfiddle.net/SxKh6/


Or even faster with plain JavaScript:

var li = document.getElementsByTagName('li');
for (var i = li.length; i-- ;) {
    li[i].parentNode.appendChild(li[i]);
}

DEMO: http://jsfiddle.net/SxKh6/1/

VisioN
  • 138,460
  • 30
  • 271
  • 271
3

Many ways, one of them:

DEMO

$('ul').append(function () {
    return $(this).children().get().reverse()
});

EDIT using append() will keep bound events to children

A. Wolff
  • 73,242
  • 9
  • 90
  • 149