473,769 Members | 6,203 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Changing an elements CSS class style with DHTML

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
9 1782
> 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.getEle mentById("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.classNa me+" ";
return cn.indexOf(" "+c+" ")!=-1;
}

function add_class(e,c) {
if (!has_class(e,c )) {
e.className=e.c lassName+" "+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
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="th is.className='c lassB';"
onmouseout="thi s.className='cl assA';"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
ph*******@treef ic.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.getEle mentById("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.classNa me+" ";
return cn.indexOf(" "+c+" ")!=-1;
}


Try these:

function has_class(e,c) {
var re = new RegExp('\\b'+c+ '\\b');
return (re.test(e.clas sName));
}

function add_class(e,c) {
if (!has_class(e,c )) {
e.className=e.c lassName+" "+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.rep lace(re,'');
}

--
Fred
Jul 23 '05 #4
> 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.rep lace(removeclas s_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
<ph*******@tree fic.com> wrote [...]:

This is Usenet, please provide proper attribution.
vvvvvvvvvvvvvvv vvvvvvvvvvvv
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
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
ph*******@treef ic.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/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #8
<ph*******@tree fic.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
Thomas 'PointedEars' Lahn wrote:
<ph*******@tree fic.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.javas cript 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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
10343
by: Jeff Thies | last post by:
I have a number of elements of "some-class". I'd like to change the styles of some-class: from ..some-class{color: red; display: block} to
1
2106
by: Rick Measham | last post by:
I can't find this anywhere, so I hope it can be done: Here's what I can do so far: 1. Certain fields have a class 'textfield' while others are 'textfieldreq'. 2. OnSubmit checks all elements and makes sure that those with 'req' have some value
14
5206
by: Holden Caulfield | last post by:
Hi there, for IE 5+ I need to be able to change certain TD tags´ background colors, and can´t figure out how to do it... For instance, in a table with 25 cells, somewhere between 5 or 10 will need the bgcolor to change at the same time when a user clicks a button. Right now only one changes when I use something like this... document.getElementById(´cellchange´).style.backgroundColor = "FFFFFF" ** (Note, this is not the EXACT code, I...
2
1762
by: Pawe³ | last post by:
Is there any way I can dynamically (taking advantage of JavaScript) change the properties for classes defined in CSS styles?? Let say there's a CSS class ".regtex" and it forces the browser to display all elements of that class in red. Now I want to change this class so all elements belonging to this class are displayed in blue, however I don't want to change every single element, I just want to change the class' properties. Is it...
7
6060
by: Stefan Finzel | last post by:
Hi, is there a way to change the display property on Windows Mobile 2003 SE Mobile/Pocket Internet Explorer? See following example. Please note: visibilty property has the same problem. Is there any other way to display/undisplay parts of web pages? TIA
4
1844
by: Siah | last post by:
Hi, I wanted to dynamically update pieces of my page in the following fashion. Look at the following html code: <span id='person_23_name'> Mike </span> <span id='person_28_name'> Siah </span> <span id='person_23_name'> Mike </span> Now, I want to update the name of person #23 (person_24_name)
22
7978
by: Saul | last post by:
I have a set of radio buttons that are created dynamically, after rendered I try loop thru this set by getting the length of the set, but I keep getting an error stating the element is undefined. I am using getElelementsByName since these are radio buttons, but it seems that the dynamic element is not seen!!! This is my code... please let me know if there is anything that I am doing wrong! - thanks ---- ....
6
2290
by: reynard | last post by:
I have a page that uses this doctype <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> but when I change to this: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> it breaks my javascript. Particularly I have a code that try to set element.style.left, when I use the second doctype, FF complains "Error in parsing value for property 'left'. Declaration dropped"
3
3233
by: David Golightly | last post by:
I'm taking a stab at making CSS sparklines - see http://www.edwardtufte.com/bboard/q-and-a-fetch-msg?msg_id=0001OR&topic_id=1&topic= <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" > <head> <title>Sparklines</title> <style type="text/css">
0
10211
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9994
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9863
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7409
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6673
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3562
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.