if (!('reversed' in document.createElement('ol'))) { (function () { // run the code on each ordered list with a 'reversed' attribute. var myLists = $('ol[reversed]'), currCount = null, currChildren = null, val; myLists.each(function () { // check the existence of the start attribute if ($(this).attr('start')) { // if it exists, convert it to an integer; also ensures even decimal values work currCount = parseInt($(this).attr('start'), 10); // If it wasn't a number, it will return 'NaN'; if so, use the number of list items instead if (isNaN(currCount)) { currCount = $(this).children().length; } // do this if the start attribute is not present // the first number is derived from the number of list items } else { currCount = $(this).children().length; } // grab all the child list items currChildren = $(this).children(); // go through each list item, adding the 'value' attribute plus currCount number // then subract one from currCount so we're ready for the next one currChildren.each(function () { val = $(this).attr('value'); // here we check if a value attribute is set in the html // and we change the count accordingly if (val && !isNaN(val)) { $(this).attr('value', val); currCount = val; } $(this).attr('value', currCount); currCount = currCount - 1; }); }); }()); }
<h1>PolyFill for HTML5's Reverse Ordered Lists</h1> <p>See: <a href="http://www.impressivewebs.com/reverse-ordered-lists-html5">HTML5 Reverse Ordered Lists</a> and: <a href="http://dev.w3.org/html5/spec/Overview.html#the-ol-element">The <code>ol</code> Element</a></p> <p>(The list below is just a normal reversed list)</p> <ol reversed> <li>List item one <li>List item two <li>List item three </ol> <p>(The list below has two nested lists; one reversed, one not)</p> <ol reversed> <li>List item one <li>List item two <ol reversed> <li>Nested one <li>Nested two <li>Nested three <li>Nested four </ol> <li>List item three <li>List item four <li>List item five <ol> <li>Nested one <li>Nested two <li>Nested three <li>Nested four </ol> <li>List item six <li>List item seven </ol> <p>(No "reversed" on the list below)</p> <ol> <li>List item one <li>List item two <li>List item three <li>List item four </ol> <p>(The list below has a "start" attribute)</p> <ol reversed start=435> <li>List item one <li>List item two <li>List item three <li>List item four <li>List item five <li>List item six </ol> <p>(The reversed list below has <code>value=55</code> set on a single <code>li</code> element)</p> <ol reversed> <li>List item one <li>List item two <li value=55>List item three <li>List item four <li>List item five <li>List item six </ol> <p>(The list below uses XHTML syntax for the "reversed" attribute)</p> <ol reversed="reversed"> <li>List item one <li>List item two <li>List item three <li>List item four <li>List item five <li>List item six </ol>
body { color: #555; font-family: Georgia, "Times New Roman", serif; line-height: 1.5; } h1 { font-family: Arial, sans-serif; font-size: 1.5em; color: #555; }