How to alternate list iems with Javascript

December 10, 2005


So, TJ and I were trying to figure out a way to get the sidebar on ganb to alternate list item background colors. We did some research on possible CSS classes and pseudo classes but could not figure out a way to do it how we wanted to. So, I set out to create reusable javascript method to take care of this issue.

What I wanted:
1. alternating list item background colors
2. ability to specify which container i wanted to apply this method to (in this case a div).

So, here it is ...

<script language="javascript">

    function doLoadFunctions() {

    function setListItemAltColor (src) {
        var divWithLists = document.getElementById(src);
        var items = divWithLists.getElementsByTagName('li');
        var itemsLength = items.length;

        for ( i = 0; i < itemsLength; i++ ) {
            if ( i%2 == 0 ) { 
                items\[i\].style.backgroundColor = "#369"; 


I generally have a function that handles all onload javascript events that I call like this: body onload="doLoadFunctions()". Within function doLoadFunctions(), simply call function setListItemAltColor(src), whereas src is the container you wish to apply this to. In the example above, the div I want to apply this to is 'test2'.

There are a few interesting javascript functions I used in this code.
1. if ( i%2 == 0) -- checks to see if integer i is odd or even
2. divWithLists.getElementsByTagName('tag') returns a collection of all elements with the specified tag -- in this instance it's all 'li' tags. `


Subscribe to my mailing list