Using the Style Object for Zebra Tables with CSS and JavaScript - Building zebra tables with the style JavaScript object
(Page 3 of 4 )
As you might have guessed, using the “style” JavaScript object to alternately assign the background colors of even and odd rows of a given (X)HTML table is actually an easy process that can be accomplished with minor hassles.
Essentially, implementing this approach requires introducing only a few changes to the “buildZebraTable()” JavaScript function that you learned before, but the logic that drives this function will remain nearly the same.
So, in order to demonstrate this concept, I listed a modified version of the aforementioned “buildZebraTable()” function that uses the “style” JavaScript object to decorate the rows of a targeted table. Here’s how this function now looks:
function buildZebraTable(tableId){
var table=document.getElementById(tableId);
if(!table){return};
// get all <tbody> table elements
var tbodies=document.getElementsByTagName('tbody');
for(var i=0;i<tbodies.length;i++){
var evenFlag=false;
// get all <tr> table elements
var trows=document.getElementsByTagName('tr');
for(var j=0;j<trows.length;j++){
// assign background color to even and odd rows
trows[j].style.backgroundColor=!evenFlag?'#eeeeee':'#cccccc';
evenFlag=!evenFlag;
}
}
}
If you examine the modified signature of the above “buildZebraTable()” JavaScript function, you’ll have to agree with me that it’s extremely easy to grasp. As you can see, the function in question now uses a “style” object, instead of a CSS class, to assign different background colors to the rows of the targeted table, thus, achieving its “zebra” appearance.
Obviously, the rest of the function remains practically the same, so you shouldn’t have major problems understanding how it works. It’s fair to mention here that there are certain aspects of the function that might be improved. For instance, it could accept the background colors that will be applied to the even and odd rows of the table as input arguments, but this modification will be left as homework for you.
So far, so good. At this point you hopefully know how to build a JavaScript function that utilizes the non-standard “style” object to create simple zebra tables. But you'll most likely want to see how this function can be used in the context of a concrete example.
Thus, in the last section of this tutorial I’ll set up a hands-on example aimed at demonstrating the capacity of the recently-defined JavaScript function when it comes to constructing zebra tables dynamically.
Go ahead and read the next few lines. They’re only one click away!
Next: Using the previous JavaScript function to build a zebra table >>
More JavaScript Articles
More By Alejandro Gervasio