Lonnie Knows Everything

Alternating html table colors, in javascript!

by Lonnie on Feb.05, 2009, under Programming

Recently I was working on an e-com project where I was given a database that contained the customer’s product catalog, but the catalog contained tons and tons of html tables that contained no id’s or classes whatsoever .. they were just vanilla tables that made use of the “TH” tag for the header row, so at least i could style that without hassle.

I could easily do some styling to all the tables, but what I really wanted to do was alternate the row’s colors so that everything didn’t run together, but without a class for each row (odd/even for example) .. I couldn’t do it in CSS.

That is where Javascript comes in! read on for more..

The first thing I did in my PHP code that pulled these tables out of the database was wrap the table in a div with a class of “product_group”, then I put this HTML code in the section of the website ..

[sniplet alternating]
We have a function called getElementsByClass which works in both IE and FireFox, I’ve not tested in ALL browsers so your mileage may vary .. but this allows us to build an array of all elements within a tag of a specified class, in our case, we’re pulling in all elements contained in “product_group”.. Once we have that, we use getElementsByTagName to pull out all of the table rows (TR), and loop through them .. we then tag each one with a class of even or odd.

After you’ve done that, it’s really just matter of assigning a background color to the alternating classes you’ve set up!

Have fun!

VN:F [1.9.3_1094]
Rating: 0 (from 0 votes)

Leave a Reply



Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...