I am sure everyone has seen the JavaScript Splintered Striper, which was shown during the 2005 24 Ways to Impress Your Friends, or at least some variation of it. A quick Google for javascript striper came up with a ton of results.

Well, I ran into a little problem with the splintered striper, and I have a solution to the problem.

The problem occurred if you had multiple class names on the element you are trying to stripe. That may not make much sense, so I guess an example will suffice.

Striping Example with Problem

Say we start with the following markup:

<ul class="stripe something">
 <li>This is an odd row.</li>
 <li>This is an even row.</li>
 <li>This is an odd row.</li>
 <li>This is an even row.</li>
 <li>This is an odd row.</li>
 <li>This is an even row.</li>

We are going to pretend that the class name something actually does something useful. Then using a JavaScript addLoadEvent function, we will add the striping event to run on page load:

addLoadEvent(function() {

Essentially, we have told the striper function to stripe all list elements (lis) that are descendants of unordered lists (uls) with the class name of stripe. Then we want to apply the classes odd and even to the alternating list items.

Here is where the problem lies. Since there are two classes on the unordered list, the striper function does not recognize that it has a class name of stripe. Here is the problem in the code:

if ((parentElementClass == null)||(currentParent.className == parentElementClass)) { 

Since we are just seeing if the class name of the current element is equal to the class name of stripe, this is not true.

I have created a simple demo page with an unordered list, table, and paragraphs that are supposed to be striped.

Fixing the Striper

Really all you have to do to the JavaScript is to remove the line from above and replace with the lines below:

var pattern = new RegExp("(^| )" + parentElementClass + "( |$)");
if ((parentElementClass == null)||(currentParent.className.match(pattern))) { 

That takes the class name and splits is with a regular expression. So now you could have fifty class names on the element, and it will still work

Here is a little demo of the improved splintered striper.

I’m sure there is another way to do that easier, so feel free to let me know if there is.