Ideal solution: CSS
What about removing all that Javascript and replacing the CSS by this:
tr:nth-child(even) {
background-color : gray;
}
tr:nth-child(odd) {
background-color : white;
}
FIDDLE
More info about the power of nth-child
can be found on CSS-Tricks. Note that this solution doesn't work in IE8, but personally I would find that acceptable. After all it's just a cosmetic aid, and users of such an old browser can either use your site without it, or upgrade their browser.
Fixing your Javascript
Your Javascript solution could work as well, by the way, but it has some errors. First of all if (document.getElementByTagName)
just checks whether the function getElementByTagName
exists, while I think you planned on executing it to get the table or the rows.
It works better like this:
function Foo(id) {
var $rows = $('#' + id + ' tr');
for (var i = 0; i < $rows.length; i++) {
if (i % 2 == 0)
$rows[i].className = "even";
else $rows[i].className = "odd";
}
}
FIDDLE
Other issues left to solve in Javascript
I removed the :not(:hidden)
part, because that is (another) issue that prevents this code to work for the second tabsheet. If you need this because you want to be able to show or hide rows, you have to take a couple of things into account:
- There should be no spaces in that selector, otherwise you'll be selecting the cells and the result will be a checker board look, so it should be
tr:not(:hidden)
.
- If you are coloring the cells, it won't work for the second tab, because that tab is hidden by the time you call Foo. To solve this, you can reverse the calls to
Foo
and to $.tabs
. That way, all tabs will still be visible when you call Foo
.
Code:
$(function () {
Foo("searchMe1"); // This first
Foo("searchMe2");
$("#tabs").tabs(); // Then this.
- You will bump into another problem if you are dynamically going to hide rows. It will mess up your coloring. You would have to call Foo every time you do to re-apply the classes. That also means that Foo needs to remove the previously assigned classes as well, otherwise you'll have both. This might need some work. :)
Note that all these problems won't exist with the CSS solution. Hidden rows are just not taken into account. See for instance THIS FIDDLE where Captain America is hidden.