Enrich Your HTML Tables with JavaScript Progressive Enhancement

Tabular headaches. Ever had one? Ivan Pepelnjak can relate because he has struggled with table formatting for years. But he has figured out how to use the JavaScript Progressive Enhancement technology to simplify the formatting of web pages and make lively, good-looking HTML tables.

Like this article? We recommend

I’ve been struggling with table formatting for years. Although I could
use Cascading Style Sheets (CSS) to automate most of my other formatting/design
scenarios, tables remained elusive. For example, the simplest requirements
(alternate background on even/odd rows and borders between columns) required
manually applying CSS classes to half the rows and at least first or last
column

While fixing the server-side scripts to apply the necessary classes to the
table rows and cells is usually easy, the tables produced manually remain a huge
pain. Just imagine adding a row in the middle of a long table; all the
subsequent rows would have to be fixed.

Tabular Headaches

With no obvious short-term CSS advances that would help me solve this
problem, I finally gave up and decided to use client-side JavaScript to add the
final design touches to the tables. Obviously, the HTML markup itself should
produce reasonably acceptable tables with JavaScript progressive enhancement adding the final touches.

To start the project, I defined a new CSS class that would be applied to the
whole table and a number of CSS rules that defined the default formatting of
cells in the table:

The header cells would have gray background and left, right, and bottom
borders.

All the other table cells would have left and right borders.

Furthermore, I had to define additional classes to be applied with the
JavaScript code to enhance the table:

The OddRow and EvenRow classes for the table rows

The FirstColumn and LastColumn classes for the first and
last cell in the row

Note: As the left and right borders are applied to HTML
elements (table cells), you can use CSS classes (the FirstColumn and LastColumn classes) to remove the unwanted attributes (left and right
borders). If the borders were defined in a CSS class, the border definitions in
the FirstColumn and LastColumn classes would have to contain
the !important keyword to override the previous rule.