Welcome to WebmasterWorld Guest from

Forum Moderators: not2easy

Message Too Old, No Replies

Setting row styles dynamically

7:04 pm on Feb 5, 2007 (gmt 0)

New User

10+ Year Member

joined:Jan 11, 2007
votes: 0


Is it possible to set the style class of a row dynamically?

Actually I want to apply different style for each rows .

for example:my first row bgcolor is green ,my second row bgcolor is red,

my third row bgcolor is blue and so on...

lam doesn't know how many rows a table has because it is dynamic.

8:46 pm on Feb 5, 2007 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
votes: 24

You could use JavaScript to get the collection of <tr> elements, then iterate through the collection appending a class to every other one.
10:46 pm on Feb 5, 2007 (gmt 0)

Full Member

10+ Year Member

joined:Dec 25, 2003
votes: 0

If by dynamic you mean server side, you could assign a different class to each group. There's also:


But afaik, support is limited to Konqueror 3.4+ ([en.wikipedia.org ])

I guess it's time for everybody to move to Linux. ;)

11:19 pm on Feb 5, 2007 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:June 26, 2004
votes: 0

Actually mep the correct code would be:

tr:nth-child(3n) { background-color: red; }
etc. etc.

element:nth-child(n) selects an element when it is the nth-child, not the nth-child of an element.

It looks like the next release of Opera [my.opera.com] will support this syntax as well, which will be nice.

12:27 am on Feb 6, 2007 (gmt 0)

Full Member

10+ Year Member

joined:Dec 25, 2003
votes: 0


Thanks for the correction; I guess the "child" part threw me off. The funny thing is, a week or two ago I was experimenting and wrote a test page for nth-child, and there I used it correctly.

I suppose if I really wanted to use tbody instead on tr I could write:

tbody>*:nth-child... :)

Good new about Opera; it's a wonderful browser and I really like it, but I almost never seem to use. Go figure.

6:13 pm on Feb 6, 2007 (gmt 0)

Junior Member

10+ Year Member

joined:Sept 27, 2006
posts: 54
votes: 0

This should do the trick. You could easily modify this to color all tables.


<script language="javascript">
var tableRowColors = ['#00FF00','#FF0000','#0000FF'];

function colorTableRows(table_id) {
if (!document.getElementById(table_id)) return false;
var table = document.getElementById(table_id);
var rows = table.getElementsByTagName('TR');
var currentColorIndex = 0;
for (var i=0;i<rows.length;i++) {
if (currentColorIndex == tableRowColors.length) currentColorIndex = 0;
rows[i].style.backgroundColor = tableRowColors[currentColorIndex];


<body onload="colorTableRows('test_table');">

<table id="test_table">