Tutorials
jQueryThere may be times when we want to apply more complex striping. For example, we can apply a pattern of three alternating row colors rather than just two. To do so, we first need to define another CSS rule for the third row. We'll also reuse the odd and even styles for the other two, but add more appropriate class names for them:
To apply this pattern, we start the same way as the previous example—by selecting all rows that are descendants of a
, but filtering out the rows that contain aTo make use of the index, we can assign our three classes to a numeric key: 0, 1, or 2. We'll do this by creating an object, or map:
Finally, we need to add the class that corresponds to those three numbers, sequentially, and then repeat the sequence. The modulus operator, designated by a %, is especially convenient for such calculations. A modulus returns the remainder of one number divided by another. This modulus, or remainder value, will always range between 0 and one less than the dividend. Using 3 as an example, we can see this pattern:
3/3 = 1, remainder 0.
4/3 = 1, remainder 1.
5/3 = 1, remainder 2.
6/3 = 2, remainder 0.
7/3 = 2, remainder 1.
8/3 = 3, remainder 2.
And so on. Since we want the remainder range to be 0 – 2, we can use 3 as the divisor (second number) and the value of index as the dividend (first number). Now we simply put that calculation in square brackets after classNames to retrieve the corresponding class from the object variable as the .each() method steps through the matched set of rows:
With this code in place, we now have the table striped with three alternating background colors:

We could of course extend this pattern to four, five, six, or more background colors by adding key-value pairs to the object variable and increasing the value of the divisor in classNames[index % n].