adding a second class name to an element

J

Jeff Gutsell

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'.

Jeff
Firefox Rules
 
M

Martin Honnen

Jeff Gutsell wrote:

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'.

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:
https://bugzilla.mozilla.org/show_bug.cgi?id=254337
 
T

Thomas 'PointedEars' Lahn

Martin said:
That should work (if theElement is a reference to an HTML element object).

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).
The only problem is that Mozilla/Firefox currently have a bug where
theElement.className = 'Class1 ';
theElement.className += 'Class2';
results in className being 'Class1Class2' [...]

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.


PointedEars
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top