By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,299 Members | 1,225 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,299 IT Pros & Developers. It's quick & easy.

Changing an elements CSS class style with DHTML

P: n/a
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

Jul 23 '05 #1
Share this Question
Share on Google+
9 Replies

P: n/a
> 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.

Jul 23 '05 #2

P: n/a
bi******@yahoo.co.uk wrote:
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).
--
Rob
Jul 23 '05 #3

P: n/a
ph*******@treefic.com wrote:
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;
}


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,'');
}

--
Fred
Jul 23 '05 #4

P: n/a
> 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.

Jul 23 '05 #5

P: n/a
<ph*******@treefic.com> wrote [...]:

This is Usenet, please provide proper attribution.
vvvvvvvvvvvvvvvvvvvvvvvvvvv
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


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

Jul 23 '05 #6

P: n/a
I wrote:
I generally try to avoid += after a nasty incident where it did an
increment rather than a string append
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).
I now use "-=-" for increment

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.

Jul 23 '05 #7

P: n/a
ph*******@treefic.com writes:

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:
A string containing only digits is still a string. The problem comes
when the programmer forgets what type the value is. It's a problem,
but it's not like the language changes strings to numbers without
telling you.
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?).
That's because it's parsing the string into a number. It calls for
input validation, just as any other handling of user input, but
the type is not the problem.
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.
Yep, if the programmer can't keep track of the types of his values,
Javascript is permissive enough to let him hang himself :).
It's one of the advantages of statically typed languages, that they
safeguard you from yourself.
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).


A classic :).
I now use "-=-" for increment


Cute!
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #8

P: n/a
<ph*******@treefic.com> wrote [...]:
I wrote:
I generally try to avoid += after a nasty incident where it did an
increment rather than a string append
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.
Whenever a string operand is involved,
the other operand of `+=' is converted to string and so concatenation

is

^^^^
performed rather than addition.


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?
I now use "-=-" for increment

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

Jul 23 '05 #9

P: n/a
Thomas 'PointedEars' Lahn wrote:
<ph*******@treefic.com> wrote [...]:
I wrote:
I generally try to avoid += after a nasty incident where it did an
increment rather than a string append


And Thomas 'Pointed Ears' Lahn replied:

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?
Jul 23 '05 #10

This discussion thread is closed

Replies have been disabled for this discussion.