0

I have html like this:

<ul id="list">
  <li class="item">a</li>
  <li class="item">b</li>
  <li class="item">c</li>
</ul>

What I'd like to accomplish using jQuery is to have the order rotated. So after one call the resulting html would be:

<ul id="list">
  <li class="item">c</li>
  <li class="item">a</li>
  <li class="item">b</li>
</ul>

And after another ...

<ul id="list">
  <li class="item">b</li>
  <li class="item">c</li>
  <li class="item">a</li>
</ul>

And so on. What is the proper way to accomplish this?

Ray Cheng
  • 12,230
  • 14
  • 74
  • 137
Jon Lachonis
  • 911
  • 1
  • 8
  • 18

3 Answers3

3

Pop the last item off the list and prepend it to the list like this:

var $list = $('#list');
$list.find('.item:last').prependTo($list);

This is a case of micro-optimization, but as long as we have to create 2 jquery objects (and there's no easy way around that), declaring the list first, then using it to limit the scope of the search for the item with find should be faster than using 2 selectors with the document as the search scope.

Faust
  • 15,130
  • 9
  • 54
  • 111
1
$("#list li:last").insertBefore("#list li:first")

DEMO

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Get the last item and prepend it.

$('#list li').last().prependTo('#list');

DEMO

Kyle Needham
  • 3,379
  • 2
  • 24
  • 38