Leading spaces in class names not added

If you add a class name with a leading space to an element that doesn't yet have a class name, Mozilla ignores the leading space.

x.className += ' over';

This can be a problem if you use a regexp to remove the class name, including the space. The regexp doesn't work in Mozilla.

x.className = x.className.replace(/ over/,'');

Test page. Workaround is not included.
Reported by ppk.

Mozilla | Reported on 13 September 2005.

This site is no longer maintained. I’m sorry, but it’s just too much work for too little return. You can continue to browse old bug reports, though.

Search reports by browser:

Atom RSS


(Add your own)

1 Posted by Emrah BASKAYA on 13 September 2005 | Permalink

Fixing leading spaces could be applied by any user agent, so it is important we do not depend on such an approach. Also, the fact that the class name e.g. 'oversize' could also be matched by such a replace, the best way to detect (and replace) a class name is by using its boundaries (our target class name is 'over' in this example:

When one adds ' over', and then replaces 'over' with '', the space is left there, and in theory, the spaces could add up to infinity if the application is not auto-trimming. So the best replace method would be to match by boundaries, and then do a space removing replace, e.g.:

This regex seems to be bullet-proof, and handles things correctly even when there are several 'over's one after another.

It is quite important that we take a semantically correct approach and watch for true word boundaries.

2 Posted by Tino Zijdel on 14 September 2005 | Permalink

Thereby: not only a space is a valid delimiter for multiple classes; any whitespace character is valid.
I normally use this regexp to match a certain classname:
or just use my classdealer functions: http://therealcrisp.xs4all.nl/meuk/classdealer.js

3 Posted by Rowan Lewis on 18 September 2005 | Permalink

Using something like /( )?classname/ would do the job, wouldn't it?

4 Posted by Klaus Paiva on 16 October 2005 | Permalink

You could, manually, add both the spaces (before and after the class name) with:

x.className = (' ' + x.className + ' ').replace(/ over/,'');

Nice and easy.