adding a second class name to an element

Discussion in 'Javascript' started by Jeff Gutsell, Nov 8, 2004.

  1. Jeff Gutsell

    Jeff Gutsell Guest

    Occasionally, in creating a static page I have assigned two classes to
    an element. For example: "class = 'BodyText Note'." It's a neat way
    of streamlining my stylesheets.

    However, I have never been able to use JavaScript to dynamically add a
    second class to an element. I'm guessing that this involves some
    string concatenation, and I must be making some silly mistake. The
    type of approach I've tried has been:
    theElement.className = 'AClass' + ' ' + 'AnotherClass'.

    Firefox Rules
    Jeff Gutsell, Nov 8, 2004
    1. Advertisements

  2. Jeff Gutsell wrote:

    That should work (if theElement is a reference to an HTML element object).
    The only problem is that Mozilla/Firefox currently have a bug where
    theElement.className = 'Class1 ';
    theElement.className += 'Class2';
    results in className being 'Class1Class2' but your assignment above
    should still work.
    The bug report is here:
    Martin Honnen, Nov 8, 2004
    1. Advertisements

  3. And the more reasonable

    theElement.className = 'AClass AnotherClass'.

    also works at least in Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.5)
    Gecko/20041128 Firefox/1.0 (Debian package 1.0-4).
    Well, I do not consider this a bug, rather a misconception. Leading and
    trailing whitespace should be removed from the value after assignment and
    on retrieval (as it serves no greater purpose in the DOM). Note that

    a.b += c;

    is a shortcut for

    a.b = a.b + c;
    (that includes reading the property)

    So the only proper way to append a style class reference should be

    theElement.className = 'Class1';
    theElement.className += ' Class2';

    which works, as described in Bugzilla.

    Thomas 'PointedEars' Lahn, Dec 12, 2004
    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.