[Javascript] Changing the CSS class of an element

Hakan Magnusson hakan at backbase.com
Tue May 18 11:37:17 CDT 2004


It's the way of doing it. Also remember the previous discussion on the 
list regarding multiple classes on one element. This is perfectly valid:

document.getElementById('mytablecell').className = "myClass yourClass";

mytablecell will then get the style definitions in both classes, and if 
you have overlapping properties, the ones in yourClass will be used 
(since it is the last one defined in your class attribute)

Useful if you want to have a "disabled" class, for example, that only 
changes the background- and forground colors to a "disabled look".

Sorry about linebreaks.

=========== style ===========
.myCell {
	padding: 4px;
	background-color: #E0E0FE;
	color: #000000;
}
.disabledCell {
	background-color: #C0C0C0;
	color: #808080;
}
=========== /style ===========

=========== script ===========
// This is the default cell
document.getElementById('mytablecell').className = "myCell";
// This cell is disabled, it will still have the padding
// defined in myCell, but the background- and foreground
// colors will be in low contrast gray (as defined in the
// latter class, disabledCell)
document.getElementById('mytablecell').className = "myCell disabledCell";
=========== /script ===========

Regards,
H

Peter Brunone wrote:
> Hi Terry,
> 
>    I'm not sure if this holds true for all other browsers (you can find out pretty quickly by trying it), but in IE, the syntax would be
> 
> document.getElementById('mytablecell').className = "myNewClass"
> 
> Cheers,
> 
> Peter
> 
> 
> Original Message:
> 
>>From: Terry Riegel <riegel at clearimageonline.com>
> 
> 
>>Is there a way to change the class of an element
>>
>>For example:
>>
>>I would like to change
>><td class="blue" id="mytablecell">
>>to
>><td class="green" id="mytablecell">
>>
>>currently I am doing something like this.
>>
>>document.getElementById('mytablecell').style.backgroundColor = 
>>'#ffffff';
>>
>>I would prefer to change the whole style if I can then I can change a 
>>lot of things at once.
>>
>>
>>Terry Riegel
>>-----------------
>>MAILKEY: 2524427349
> 
> 
> 
> _______________________________________________
> Javascript mailing list
> Javascript at LaTech.edu
> https://lists.LaTech.edu/mailman/listinfo/javascript
> 
> 



More information about the Javascript mailing list