0

I have some list - it's generated in alphabetical order

<div class='list'>
  <ul>
    <li><a  href="/home/fresa/Desktop/task/page.html">2011</a></li>
    <li><a  href="/home/fresa/Desktop/task/page.html#?topic=2013">2012</a></li>
    <li><a  href="/home/fresa/Desktop/task/page.html#?topic=2012">2013</a></li>
    <li><a  href="/home/fresa/Desktop/task/page.html#?topic=2012">2014</a></li>
    </ul>
</div>

and I trying to reverse it from back to front:

var arr = [];
arr.push($('.list ul li'));
$('.list ul').html(arr.reverse());

but it steel displays in not correct order

how to fix it, and what i'm doing wrong

Mongo
  • 151
  • 7
  • 1
    possible duplicate of [jQuery reversing the order of child elements](http://stackoverflow.com/questions/5347839/jquery-reversing-the-order-of-child-elements) – Paul Roub Oct 16 '14 at 22:05
  • It's because your `arr.push()` is not working as you expect it to. It is pushing one jQuery object onto your array, not the 4 individual elements you expect. I added an [answer below](http://stackoverflow.com/a/26414761/361762) albeit after several others. – Dave Oct 16 '14 at 22:08

3 Answers3

3

Try this:

$('.list ul li').each(function(){
    $(this).prependTo($(this).parent())
});

It'll loop through each item and add it to the beginning of the list. See a fiddle here:

http://jsfiddle.net/afsmonr1/

Jake
  • 4,014
  • 8
  • 36
  • 54
1

Try this

var list = $(".list ul li").get().reverse();
$(".list ul").empty();
$.each(list, function(i) {
  $(".list ul").append("<li>" + list[i].innerHTML + "</li>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div class='list'>
  <ul>
    <li><a href="/home/fresa/Desktop/task/page.html">2011</a>
    </li>
    <li><a href="/home/fresa/Desktop/task/page.html#?topic=2013">2012</a>
    </li>
    <li><a href="/home/fresa/Desktop/task/page.html#?topic=2012">2013</a>
    </li>
    <li><a href="/home/fresa/Desktop/task/page.html#?topic=2012">2014</a>
    </li>
  </ul>
</div>
Bojan Petkovski
  • 6,835
  • 1
  • 25
  • 34
1

It's because your arr.push() is not working as you expect it to. It is pushing one jQuery object onto your array, not the 4 individual elements you expect.

If you set your array as follows it will work:

$(function() {
  var arr = $('.list ul li').get();
  $('.list ul').html(arr.reverse());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class='list'>
  <ul>
    <li><a  href="/home/fresa/Desktop/task/page.html">2011</a></li>
    <li><a  href="/home/fresa/Desktop/task/page.html#?topic=2013">2012</a></li>
    <li><a  href="/home/fresa/Desktop/task/page.html#?topic=2012">2013</a></li>
    <li><a  href="/home/fresa/Desktop/task/page.html#?topic=2012">2014</a></li>
  </ul>
</div>
Dave
  • 10,748
  • 3
  • 43
  • 54