Create a Reverse-Order Ordered List Using jQuery

Earlier today I came across a small website coding “problem”, which required me to create a “top-ten” list of items in reverse order for a client.

Usually ordered lists are very simple to in XHTML create using the following code:

  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
  <li>List item 4</li>
  <li>List item 5</li>

Which will produce the following ordered list:

  1. List item 1
  2. List item 2
  3. List item 3
  4. List item 4
  5. List item 5

Unfortunately HTML won’t automatically handle reverse numbering. Adding the numbers manually into a standard unordered list looked messy and I wanted a solution that would automatically renumber the list in case anyone else came along and added more items … jQuery to the rescue.

Using some of the usual jQuery magic we can add the following code to the head of the document:

$(document).ready(function() {   

   var countli = $('ol > li').size();
   $("ol > li").each(function(i) {
         var attrvalue = countli - i;

This will automatically reverse order all of the items in the ordered lists on the web page by adding the “value” attribute to each list item.

See demo for creating a reverse order ordered list using jQuery.

1 Comment

  • This post was mentioned on Twitter by Richard Hawkesford.

Leave a comment

To add code to your comments wrap the code text in [text][/text] tags