Thursday 7 October 2010

Nested ordered list

To my surprise I found out the other day that there does not seem to be a html+CSS way to create a nested ordered list. I mean, the typical index, something like this:
1. Europe
1.1 Germany
1.1.1 Hesse
1.1.2 Bavaria
1.2 UK
2. Asia

Using the normal html structure you would get something like this:

1 Europe
1 Germany
1 Hesse
2 Bavaria
2 UK
2 Asia

so, you have to resort to JavaScript to get the right numbering. It's pretty simple, and much more if you're using jQuery's magic, but anyway I think it can be helpful (at least as my personal repository), so here it is:

(you also need a change to your html, instead of <ol> elements you'll have to use <ul>, as it's javascript who's going to take care of all the numbering)



function orderNestedList($ulItem, curValue)
{
$ulItem.children("li")
.each(function(index)
{
var newValue = curValue + (++index) + ".";
$(this).prepend(newValue);
var children = $(this).children("ul");
if (children.length > 0)
orderNestedList($(children[0]), newValue);
});
}


you can see it at work here

No comments:

Post a Comment