Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
Like this article? We recommend

Add the Final Touches

When we defined a comprehensive set of CSS classes, we did the majority of the work—the HTML table in its default appearance already looks quite good and the JavaScript code will just add the final touches. Since the changes that have to be applied to the table formatting with JavaScript are already defined in CSS rules, the actual work to be done is quite simple:

  1. Find all HTML TABLE elements with class equal to printout.
  2. For all odd rows in the selected HTML tables, add the OddRow class to the list of CSS classes (and similarly for the even rows).
  3. In every row, add the FirstColumn class to the first cell and the LastColumn class to the last cell.

The use of X library also greatly reduces the JavaScript code size:

  • The xGetElementsByClassName function finds all HTML tables with the printout class. This function has a callback parameter, allowing us to further optimize the code.
  • The xGetElementsByTagName function is used to find all rows as well as the TH elements in the current row.
  • The xAddClass function adds a CSS class to an HTML element.

The JavaScript code is included in the following listing (and you can also download it from my web site):

function enrichTable(table) {
 var rows = xGetElementsByTagName("TR",table);
 var rcnt = 0; // odd-even row count

 for (var rc = 0; rc < rows.length; rc++) {
  var row = rows[rc];
  if (xGetElementsByTagName("TH",row).length > 0) {
   rcnt = 0; // reset the odd-even count at header rows
  } else {
   xAddClass(row,rcnt % 2 == 0 ? "EvenRow":"OddRow");
  if (row.cells.length) {
   xAddClass(row.cells[row.cells.length - 1],"LastColumn");

function enrichPrintoutTables() {

Last, but definitely not least, the JavaScript code has to be executed after the web page is loaded, so we need to define the enrichPrintoutTables function as an on-load event handler with the following JavaScript function call:

  • + Share This
  • 🔖 Save To Your Account