Changing an elements CSS class style with DHTML

Discussion in 'Javascript' started by bissatch, May 17, 2005.

  1. bissatch

    bissatch Guest


    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.


    bissatch, May 17, 2005
    1. Advertisements

  2. bissatch

    phil_gg04 Guest

    Is it possible to change the class style of an HTML element using
    Easy, just change the className property of the element:
    <td id="foo" class="a">

    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;

    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_gg04, May 18, 2005
    1. Advertisements

  3. bissatch

    RobG Guest

    If you just want to change the class:

    <style type="text/css">
    .classA {background-color: red;}
    .classb {background-color: blue;}
    <div style="width: 100px; height: 100xp;"

    But if you want to change the actual style rule, that's a different
    matter (but not impossible).
    RobG, May 18, 2005
  4. bissatch

    FredOz Guest

    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 += " " + c;
    function remove_class(e,c) {
    var re = new RegExp ('\\b'+c+'\\b');
    e.className = e.className.replace(re,'');
    FredOz, May 18, 2005
  5. bissatch

    phil_gg04 Guest

    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.
    phil_gg04, May 18, 2005
  6. This is Usenet, please provide proper attribution.
    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.
    You use a syntax error to achieve anything? I sincerely doubt that.
    That would be better, indeed.
    They do.

    Thomas 'PointedEars' Lahn, May 23, 2005
  7. bissatch

    phil_gg04 Guest

    And Thomas 'Pointed Ears' Lahn replied:
    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
    Try this:

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

    function main() {

    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_gg04, May 23, 2005
  8. 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.
    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 .
    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.
    alert([x, typeof x, x.length]);

    certainly will.
    See the *real* problem?
    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 `+='.

    Thomas 'PointedEars' Lahn, May 24, 2005
  9. bissatch

    Randy Webb Guest

    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?

    comp.lang.javascript FAQ - & newsgroup weekly
    Answer:It destroys the order of the conversation
    Question: Why?
    Answer: Top-Posting.
    Question: Whats the most annoying thing on Usenet?
    Randy Webb, May 24, 2005
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.