1

I'm trying to get an unordered list to show its items in a reversed order. In other words, getting this:

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

To show:

  • Three
  • Two
  • One

I tried jQuery with this answer: jQuery reversing the order of child elements

However, it didn't work for me for some reason. (I put it in a .html file, and also I tried using <script src="script.js"></script>)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>

var list = $('ul');
var listItems = list.children('li');
list.append(listItems.get().reverse());

</script>

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

Additionally, that answer was from 4 years ago, so I'm wondering if there's now a better solution?

Community
  • 1
  • 1
Panpaper
  • 451
  • 1
  • 6
  • 16

1 Answers1

1

Your script should be executed after the DOM (Document Object Model) is fully loaded. Try replacing your script by

$(document).ready(function () {
    var list = $('ul');
    var listItems = list.children('li');
    list.append(listItems.get().reverse()); 
});

You can read more here: https://learn.jquery.com/using-jquery-core/document-ready/ for more information.

alepeino
  • 9,551
  • 3
  • 28
  • 48
  • Or simply move the code to the end of the page before the closing body tag. – j08691 Sep 29 '15 at 14:59
  • Yes, that's right. It is however a good practice to call the script explicitly after document is ready. Also, this encloses the variables declaration within a function, thus preventing the global declaration. – alepeino Sep 29 '15 at 15:01
  • In general yes, a good practice. But not a requirement for this basic example. – j08691 Sep 29 '15 at 15:07
  • You can also use the small code in this [fiddle](http://jsfiddle.net/v00gr3gt/2/), working without jquery. – Amessihel Sep 29 '15 at 15:18