Alternating Ordered List Item Styles

We have Policies and Procedures document that we are making available on our website.  This document in its entirety easily spans several hundred pages and has a pretty lengthy table of contents. 

To help make this easy to navigate and easier to consume we are posting several of the larger topics as individual documents and making them available from a linked table of contents that is created as a web page.

The requirement is that the table of contents uses different numbering styles at each indentation.  So, for instance, the outline below:

Topic A

   Sub-topic A.1

   Sub-topic A.2

      Sub-topic A.2.1

      Sub-topic A.2.2

Topic B

Topic C

would become:

1. Topic A

   a. Sub-topic A.1

   b. Sub-topic A.2

      i. Sub-topic A.2.1

      ii. Sub-topic A.2.2

2. Topic B

3. Topic C

This document isn’t maintained in a database yet so for now the table of contents is created in good old fashioned HTML.  Using a standard <ol> (ordered list) element in HTML looks initially like this:

  1. Topic A
    1. Sub-topic A.1
    2. Sub-topic A.2
      1. Sub-topic A.2.1
      2. Sub-topic A.2.2
  2. Topic B
  3. Topic C

The way to change the numbering style is by using the CSS list-style-type style on the <ol> element with various options such as decimal, lower-alpha and lower-roman.  You can find a great example of this at w3schools.  So, I could manually change the list style of each <ol> tag based on how much it was indented, but this would be a pain to maintain.  Anytime we changed the layout I would have to change the list-style-type styles and be sure to keep everything consistent.  I thought this would be a perfect place to use jQuery.

Using jQuery I was able to define an array of the types I wanted to use.  jQuery would then find all the <ol> and nested <ol> elements and change the style for each indentation.  Once done I could simply maintain the table of contents and jQuery would handle the styling. I couldn’t find any jQuery plug-ins that did this so here is the code I came up with.  If I end up using more than a couple of times I’ll probably create a plug-in for it.

1: function styleOutline() {
2: // List-item-styles we would like to use
3: var olStyles = [‘decimal’, ‘lower-alpha’, ‘lower-roman’];
4:
5: // Process the parent element.
6: styleOl($(‘ol:first’), 0);
7:
8: function styleOl(element, styleIndex) {
9: // Apply style
10: element.css(‘list-style-type’, olStyles[styleIndex % olStyles. length ]);
11:
12: // Call recursively for each nested ol
13: element.children().each(
14: function (i) {
15: var ol = $( this ).children();
16: if (ol) {
17: styleOl(ol, styleIndex + 1);
18: }
19: }
20: );
21: }
22: }
23:

This works great and took me only a couple of minutes to do. Definitely an improvement over the manually written way.  I hope this helps someone else out there!