My Books

Text Processing with JavaScript

Solve complex text validation, extraction, and modification problems efficiently in JavaScript.

Modern Async JavaScript

Delve into async features of JavaScript from ES2020 through ESNext. Start building custom asynchronous iterators and generators, and more for fast, lean code.

JavaScript Brain Teasers

Ready to test your JavaScript skills? Challenge yourself with these brain-teasing puzzles, supercharge your learning journey, and emerge as a JavaScript pro.

Alternating Row Colors in jQuery

Alternating row colors in jQuery can be easily done using :even and :odd selectors. Let's apply these selector to a list and see the effect.

Last week I explained how to color odd and even rows in a table using CSS. today I’m going to show you how you can have the same effect in jQuery. There are two great jQuery selectors which allows you to color alternate rows (i.e. zebra stripes), they are :even and : odd. To see this in action, let’s first define a sample html list:

<ul>
<li>css</li>
<li>html</li>
<li>javascript</li>
<li>jquery</li>
<li>mootools</li>
</ul>

Then add a style to the stylesheet for all css rows, and use an alt class for the even rows:

tr {
    background-color: white;
}
.striped {
    background-color: grey;
}

Now, by using the following jQuery code, you can attach the class to the even-numbered table rows:

$(document).ready(function() {
    $('tr:odd').addClass('stripe');
});

You might be wondering why I added tr:odd for even rows, well, the reason for that is that In javascript the first row counts as 0 (even) and the second row counts as 1 (odd), So if you wanted to color odd rows you would replace code>tr:odd with tr:even.

Have your say