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

2
  • 1
    possible duplicate of jQuery reversing the order of child elements Commented Oct 16, 2014 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 albeit after several others. Commented Oct 16, 2014 at 22:08

3 Answers 3

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/

Sign up to request clarification or add additional context in comments.

Comments

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>

Comments

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.