An Improved Approach to Building Zebra Tables - Working with tables that contain multiple tbody sections
(Page 3 of 4 )
In accordance with the concepts that I deployed in the section that you just read, the definition of the previous “buildZebraTable()” JavaScript needs some tweaks, since it must be provided with the ability to construct zebra tables that include multiple <tbody> sections too.
Fortunately for you and me, introducing this modification to the aforementioned JavaScript function is a pretty straightforward process. It consists basically of adding a few lines of code aimed at checking for the existence of <tbody> tags inside the markup of the zebra table being styled.
However, listing the improved signature of this function will possibly help you to understand this concept. Therefore, take a look at the following code sample, which shows how the “buildZebraTable()” function is now capable of working seamlessly with zebra tables that contain multiple <tbody> tags within the corresponding markup:
// improved definition of the 'buildZebraTable()' function
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 CSS class to even and odd rows
trows[j].className=!evenFlag?'oddrow':'evenrow';
evenFlag=!evenFlag;
}
}
}
As you can see, the logic that drives the above “buildZebraTable()” function is capable of dealing directly with (X)HTML tables that include more than one <tbody> header. First, it checks for the existence of these elements in the table, then it iterates over them, and finally it accesses the inner rows in order to style them alternately via the respective “oddrow” and “evenrow” CSS classes. That was really simple to understand, wasn’t it?
So far, so good. Now that you've hopefully grasped how the previous JavaScript function does its thing, it’s time to move forward and see how it can be included in a sample (X)HTML file. We will attach it to a specific table, as well as to the pertinent CSS styles.
Are you curious about how this will be done? Jump ahead and read the next few lines. I’ll be there waiting for you.
Next: Setting up a final hands-on example >>
More JavaScript Articles
More By Alejandro Gervasio