HTML question

What is a good way of accomplishing the following:

There is an HTML table where each cell gets an ID (say from 1 to 5). More than one cell can have the same ID.

I would like to have a button on the page that, when pressed, toggles the table between two states

  1. All cells have the same background color
  2. Cells have a background color based on their ID (e.g. 1 is white, 2 is red, 3 is blue…)

Can this be done using a combination of Javascript and HTML?
Do I need to use CSS?

I am somewhat familiar with Javascript and HTML, but have never used CSS.

It is not valid HTML for more than one element on a page to have the same ID. However, multiple elements can be of the same class.

You could write some Javascript to find all the elements of a given class, and set its background color to whatever you like. You can use a function like this to retrieve a list of all the elements with a particular class name, then loop over them one by one and alter the background color.

You’d use some combination of Javascript and HTML. CSS is optional, but I’d recommend it because it makes a lot of sense here. You can read through a basic tutorial if you’d like.

Anyway, here’s a working sample of what you wanted:


<!--This is the CSS section, where you define the "look" of your page elements, including your table cells.
The way this works is that each cell will have two classes:
1. Either ".multicolor" or ".plaincolor".  A JavaScript button/function will toggle between these two sets.
2. When the script sets the cells to ".multicolors" mode, a further set of subclasses from ".class1" to ".class5" will give each subclass a unique color.
	/* This section just makes the table easier to see. It does not affect script functionality. */
	#mytable {border: 1px dahed blue}
	#mytable * {padding: 5px}

	This is the important part.  When the cells are in multicolor mode (done via the script that gives them all the ".multicolor" class),
	each subclass from ".class1" to ".class5" has a different color.  Colors can be defined using regular HTML color codes or names.
	.multicolor .class1 {background-color: #DDF}
	.multicolor .class2 {background-color: #CCD}
	.multicolor .class3 {background-color: #AAB}
	.multicolor .class4 {background-color: #889}
	.multicolor .class5 {background-color: #667}
	When the cells are in plaincolor mode, we can override all subclass colors (".class1" to ".class5") at once by using the parent class,
	".plaincolor", in conjunction with the * (asterisk) wildcard, which selects all sub-elements.  This has to do with CSS inheritance rules
	that I won't get into here.
	.plaincolor * {background-color: lightblue}


These two functions toggle the table between two color schemes.

They accomplish this by setting the table to one of two CSS classes, either ".multicolor" or ".plaincolor".  You can define the actual colors used in the <style> section above, not here in the script.
function setPlainColors() {document.getElementById("mytable").className = "plaincolor";}
function setMultiColors() {document.getElementById("mytable").className = "multicolor";}

//Just a flag for the next function
var ToggleFlag=0; 

//The actual toggle function
function toggleColors() {
	if (ToggleFlag == 0) {setPlainColors(); ToggleFlag = 1} //If the table is currently multicolor, make it plain and set the flag.
	else {setMultiColors(); ToggleFlag = 0;} //Otherwise, make it multicolor and reset the flag



<!--The button to toggle colors.  When clicked, it runs the JavaScript function toggleColors(), as defined in the <script> section above.-->
<input type=submit value="Toggle Colors" onClick="toggleColors();">


<!--This is your actual HTML table.  Only the layout and text is defined here; colors and presentation are in the <style> section above.-->
<table id="mytable" class="multicolor">
<tr><td class="class1">This is a Class 1 Cell</td></tr>
<tr><td class="class2">This is a Class 2 Cell</td><td class="class2">This is a Class 2 Cell</td></tr>
<tr><td class="class3">This is a Class 3 Cell</td></tr>
<tr><td class="class4">This is a Class 4 Cell</td></tr>
<tr><td class="class5">This is a Class 5 Cell</td><td class="class4">This is a Class 4 Cell</td><td class="class3">This is a Class 3 Cell</td></tr>

I strongly suggest you learn CSS. Its purpose is basically to save you time. You either use a style tag like Reply here has, or load up an external .css file in the header.

<link href="stylesheet.css" rel="stylesheet" type="text/css">

You assign elements on your page either a CLASS or an ID. These are HTML properties, like HREF for A or SRC for IMG. Only one element (IMG, P, A, DIV) on a page can have the same ID name. Multiple elements, however, can share a class name.

Basically the point is that you can set an element’s height, width, text color, text size, background color, border, font, text style, etc etc using CSS. So if I want to set all the text in a paragraph to be italic and white, instead of using an I and a FONT tag, I give the table an ID or CLASS and write up the CSS.

<P ID="fancy"></P>

in the linked CSS file I write

font-style: italic;
color: white;

There’s a list of CSS properties at the W3schools page. The bit before the colon is the property, and the bit after is what it’s set to. The # goes before the ID name, a period goes before a class name. Each line must be terminated with a semi-colon, and the declared properties of an element must be contained within curly braces {}

Thanks! Using code based on the one in your link, I have accomplished what I wanted.

FYI, this is what I came up with

<script type="text/javascript">

var flag = 1;

function setColorByClass(class_name, color) 
  var els = document.getElementsByTagName("td");
  for (i = 0, j = 0; i < els.length; i++) {
    if(els*.className == class_name)
      els*.style.backgroundColor = color;

function toggle_colors()
  flag = 1-flag;

  var colors=new Array("#FFFF99", "#00FF66", "#66CCCC");

  for(cell_idx = 1; cell_idx <= colors.length; cell_idx++)
    var color = (flag == 0) ? colors[cell_idx-1] : "#FFFFFF";
    setColorByClass("cell_type"+cell_idx, color);

This looks like a more elegant way of doing it than my solution above. I’ll look into this method when things like this come up in the future.

Hey, if it works, it works =)

The problems with using Javascript are that it is a compatibility nightmare and that people tend to turn it off out of concern for popups, popunders, and bizarre show-stopping browser bugs (as in, “I just lost five hours of work to a crash!”). CSS is imperfect but simple stuff is widely supported in the browsers most people use now. (If you have to support Netscape 4, nothing can help you but suicide.)

Cite? :smiley:

This seems to be an urban legend spread the web developer community itself. While I have no empirical evidence of my own, it has been my experience that only the fearful technically competent web users actively disable Javascript as a matter of course while web surfing. And those fearful technically competent web users don’t amount to a statistical blip on the radar screen.

The real problem with using Javascript is that it is a user dependency system. If you use Javascript as a critical part of navigation, you run a serious risk of preventing the user from fully enjoying the web site if for some reason Javascript does not fully render during downloading. It also suffers from accessibility issues.

Another problem is using Javascript to verify web form behavior. This becomes a critical issue if web form is used to verify inputted sensitive data and/or the transaction requires some sort of security. In this case, the Javascript can be manipulated by the user to distort the data and/or gain unauthorized access.

Is there a way to do what I ask in the OP without any Javascript?

Even if I use CSS, there has to be a way to tell the page to toggle between two states at the press of a button. Can this be done without Javascript?

Yes. Use a server scripting language such as PHP. The topic that comes to mind is a CSS style switcher where web users change change the look/feel of a site by clicking on a link (in you case a button). has an article here that explains the PHP switcher. Ther also have an alternate version that uses Javascript.

It should not be difficult to apply the concept to what you want to do.