[Javascript] Changing the CSS class of an element
Paul Novitski
paul at novitskisoftware.com
Tue May 18 10:36:36 CDT 2004
I would add a couple of thoughts:
First, that precedence is important: you'll want to define the base state
of the object first (as Hakan did in his example), so that sub-states will
overlap its characteristics:
.CellDatagrid {...} /* sets the base properties */
.CellActive {...} /* replaces some base properties */
.CellDisabled {...} /* replaces some base properties */
Second, you can use String.replace() to toggle specific classes in a
compound class without affecting others, for example:
to begin:
obj.className = "CellDatagrid CellActive SomeOtherClass"
disable it:
obj.className = obj.className.replace(/CellActive/, "CellDisabled")
result:
obj.className == "CellDatagrid CellDisabled SomeOtherClass"
The disable function therefore doesn't need to know what other class names
might be concatenated, which is how it should be if it's to continue
working without breaking other functionality you might add in the future.
The RegExp can be enhanced to ensure that the class name being replaced is
a discrete word and not part of another longer word, and the logic can be
enhanced to cover the possibility that no active/disabled state has yet
been applied.
Paul
At 09:37 AM 5/18/2004, Hakan Magnusson wrote:
>=========== style ===========
>.myCell {
> padding: 4px;
> background-color: #E0E0FE;
> color: #000000;
>}
>.disabledCell {
> background-color: #C0C0C0;
> color: #808080;
>}
More information about the Javascript
mailing list