Changing an elements CSS class style with DHTML


B

bissatch

Hi,

Is it possible to change the class style of an HTML element using
DHTML? For example...

<td class="my_class">Text</td>

I have used DHTML to change style elements such as backgroundColor so I
assume that it can be used to change the class too.

Cheers

Burnsy
 
Ad

Advertisements

P

phil_gg04

Is it possible to change the class style of an HTML element using
DHTML? For example...
<td class="my_class">Text</td>

Easy, just change the className property of the element:
<td id="foo" class="a">
document.getElementById("foo").className="b";

Here are a couple of general-purpose functions that I use to add and
remove classes:

function has_class(e,c) {
var cn=" "+e.className+" ";
return cn.indexOf(" "+c+" ")!=-1;
}

function add_class(e,c) {
if (!has_class(e,c)) {
e.className=e.className+" "+c;
}
}

function remove_class(e,c) {
var cn=e.className;
var p=cn.indexOf(c);
if (p==-1) return;
cn=cn.substr(0,p)+cn.substr(p+c.length);
e.className=cn;
}


Note: in your example, you used an _ in the class name. Although this
is now allowed some previous versions of the CSS spec did not allow _
in class names, so for maximum cross-browser compatibility you should
avoid it. Use - instead.

--Phil.
 
R

RobG

Hi,

Is it possible to change the class style of an HTML element using
DHTML? For example...

<td class="my_class">Text</td>

I have used DHTML to change style elements such as backgroundColor so I
assume that it can be used to change the class too.

Cheers

Burnsy

If you just want to change the class:

<style type="text/css">
.classA {background-color: red;}
.classb {background-color: blue;}
</style>
<div style="width: 100px; height: 100xp;"
class="classA"
onmouseover="this.className='classB';"
onmouseout="this.className='classA';"
blah</div>


But if you want to change the actual style rule, that's a different
matter (but not impossible).
 
F

FredOz

Easy, just change the className property of the element:
<td id="foo" class="a">
document.getElementById("foo").className="b";

Here are a couple of general-purpose functions that I use to add and
remove classes:

function has_class(e,c) {
var cn=" "+e.className+" ";
return cn.indexOf(" "+c+" ")!=-1;
}

Try these:

function has_class(e,c) {
var re = new RegExp('\\b'+c+'\\b');
return (re.test(e.className));
}
function add_class(e,c) {
if (!has_class(e,c)) {
e.className=e.className+" "+c;
}
}

function add_class(e,c) {
if (!has_class(e,c)) {
e.className += " " + c;
}
}
function remove_class(e,c) {
var cn=e.className;
var p=cn.indexOf(c);
if (p==-1) return;
cn=cn.substr(0,p)+cn.substr(p+c.length);
e.className=cn;
}

function remove_class(e,c) {
var re = new RegExp ('\\b'+c+'\\b');
e.className = e.className.replace(re,'');
}
 
P

phil_gg04

e.className += " " + c;

Yes, that does save a few microseconds of download time. But I
generally try to avoid += after a nasty incident where it did an
increment rather than a string append and I spent ages debugging it. I
now use "-=-" for increment, or write it out long-hand.

As for the regexps, you might save some more microseconds of execution
time by keeping them around from one invocation to the next:

var removeclass_re = new RegExp ('\\b'+c+'\\b');
function remove_class(e,c) {
e.className = e.className.replace(removeclass_re,'');
}

I don't know if browsers actually spend any significant time compiling
regular expressions, but this would certainly be the "right way" to do
it in other languages.
 
T

Thomas 'PointedEars' Lahn

This is Usenet, please provide proper attribution.
vvvvvvvvvvvvvvvvvvvvvvvvvvv
Yes, that does save a few microseconds of download time. But I
generally try to avoid += after a nasty incident where it did an
increment rather than a string append

This could have happened only because you were (are?) not aware of property
types and automatic type conversion. Whenever a string operand is involved,
the other operand of `+=' is converted to string and so concatenation is
performed rather than addition.
and I spent ages debugging it. I now use "-=-" for increment,

You use a syntax error to achieve anything? I sincerely doubt that.
or write it out long-hand.

That would be better, indeed.
[...]
I don't know if browsers actually spend any significant time compiling
regular expressions, [...]

They do.


PointedEars
 
Ad

Advertisements

P

phil_gg04

And Thomas 'Pointed Ears' Lahn replied:
Whenever a string operand is involved,
the other operand of `+=' is converted to string and so concatenation is
performed rather than addition.

The problems and potential bugs come when you have something that you
think is a string, but it happens to contain only digits and so is a
number: e.g. phone numbers, credit card numbers and so on. (Have you
ever seem a program or web site strip leading zeros from a phone
number? Or suffer an integer overflow when you enter 20 digits?). Or,
vice-versa, you think you have a number but actually have a string;
this could easily happen if you have parsed a number out of a string
with a regexp, for example, and it's difficult to debug because
'alert(x)' will give no clue.

The incident that I mentioned before was a long time ago and I forget
the details, but it was to do with parsing CSS length units, i.e.
splitting something like "10px" into a number (10) and a unit (px);
instead of adding 1 to the length (11px) I ended up appending 1
(101px).
syntax error

Try this:

function test(a) {
var b=a; var c=a;
b+=1;
c-=-1;
if (b==c)
alert ("passed for "+a+": += and -=- both yield "+b);
else
alert ("failed for "+a+": += yields "+b+" while -=- yeilds "+c);
}

function main() {
test(1);
test(-1);
test(1000);
test("10");
}


You'll see that += and -=- have the same behaviour when their operands
are numbers. When one or other is actually a string, += does a string
append while -=- converts them to numbers first.


--Phil.
 
T

Thomas 'PointedEars' Lahn

And Thomas 'Pointed Ears' Lahn replied:

You almost got it.

1. Who is `I' in a cited *public* discussion?
2. The basics of accepted attribution are described in the newsgroup's
FAQ notes. I strongly suggest you read those (more) thoroughly.

Posting borken quotes subsequently corrected in the view of Google Groups
users are a major malfunction of the Google Groups Web interface. I
strongly suggest that either you perform manual reformatting so that quoted
lines do not exceed 72 characters per line, or stop using Google Groups for
posting and start using a newsreader application instead. GG ist still good
for research, though.
The problems and potential bugs come when you have something that you
think is a string, but it happens to contain only digits and so is a
number: e.g. phone numbers, credit card numbers and so on. (Have you
ever seem a program or web site strip leading zeros from a phone
number?

No, and such applications would be borken. Leading zeroes in phone numbers
indicate that the participant is located outside the current city (0) or
country code (00) area and thus must not be stripped automatically; this
requires the phone number to be stored (in the database) and processed (as
variable value) as a character string .
Or suffer an integer overflow when you enter 20 digits?).

What's your point? A 20-digit number where leading zeroes are allowed to be
stripped is pretty well covered by a 64 bit floating-point number
representation (but it is likely to be rounded) as used in JavaScript 1.0
and ECMAScript implementations. Other languages also introduce appropriate
long integer types. Unless the application has been improperly designed,
there is no reason for an integer overflow here.
Or, vice-versa, you think you have a number but actually have a string;
this could easily happen if you have parsed a number out of a string
with a regexp, for example, and it's difficult to debug because
'alert(x)' will give no clue.

alert([x, typeof x, x.length]);

certainly will.
The incident that I mentioned before was a long time ago and I forget
the details, but it was to do with parsing CSS length units, i.e.
splitting something like "10px" into a number (10) and a unit (px);
instead of adding 1 to the length (11px) I ended up appending 1
(101px).

See the *real* problem?
syntax error

Try this:
[...]
c-=-1;
[...]
You'll see that += and -=- have the same behaviour when their operands
are numbers. When one or other is actually a string, += does a string
append while -=- converts them to numbers first.

Now I see it, you use the `-=' operator (not `-=-') and a previously omitted
negative number as operand. That can become useful, although it alone is
less efficient than simple `+='.


PointedEars
 
Ad

Advertisements

R

Randy Webb

Thomas said:
You almost got it.

1. Who is `I' in a cited *public* discussion?

Are you actually so anally retentive that a person writing "I" does not
seem to you to be pointing at the person who wrote it?



--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Answer:It destroys the order of the conversation
Question: Why?
Answer: Top-Posting.
Question: Whats the most annoying thing on Usenet?
 

Top