Alternating Row Colours

30th October 2008

Tags : Javascript, DOM, Code Examples

I like to use alternating row columns in tables. If the tables in question are static HTML then updating the row colours, (when adding/removing/shifting rows), can become a real chore.

Using some of the wonderful W3C DOM Methods within Javascript I came up with a simple function to do all the work for me.

function doAltColours(){
	var colour1 = 'gray';	//Initial row colour
	var colour2 = '#CCCCCC';	//Alternating row colour
	//Retrieve all of the table objects on the current page
	var tables = document.getElementsByTagName('table');
	for(var i=0; i<tables.length; i++){
		var table = tables[i];
		//Check to see if this table is one we want to alter
		if(table.className == "altColours"){
			//Retrieve all of the table rows within the current table
			var rows = table.getElementsByTagName('tr');
			if(rows.length > 0){
				//Reset the current row colour
				var currCol = colour1; 
				for(var j=0; j<rows.length; j++){
					//Change this row's colour
					var row = rows[j];
					row.style.backgroundColor = currCol;
					//Toggle the current colour
					currCol = (currCol == colour1) ? colour2 : colour1;
				}
			}
		}
	}
}

All tables with the class 'altColours' will automagically be re-formatted to have alternating row colours. All we need to do is execute the preceding function after the page has finished loading. (Either using the 'onload' attribute of the body tag, or by calling the function just before the closing body tag).