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,184
  • 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
  • 18,087
  • 10
  • 53
  • 91
  • for simplicity i kept it as a normal ul, let me test this – user934902 Dec 19 '13 at 18:09
  • http://jsfiddle.net/DmT5y/1/ did not work – user934902 Dec 19 '13 at 18:10
  • turns out you have to add the method get() before reverse(); added fiddle – dezman Dec 19 '13 at 18:10
  • Use .append, not .html – Felix Kling Dec 19 '13 at 18:12
  • @FelixKling why? then I would have to remove the lis with the original order. – dezman Dec 19 '13 at 18:12
  • 2
    `.html` will create new DOM elements. You don't have to remove the elements beforehand, they are simply moved: *"You can also select an element on the page and insert it into another. [...] If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned)"* http://api.jquery.com/append/ – Felix Kling Dec 19 '13 at 18:15
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
  • 143,310
  • 32
  • 282
  • 281
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
  • 74,033
  • 9
  • 94
  • 155