[Javascript] Adding classes

Barney Carroll barney at textmatters.com
Mon Aug 13 08:02:04 CDT 2007


Ah... Brilliant - className is exactly what I was after. I'll work out 
clever concatenation when & if it comes to it :)

Thanks a lot, Liorean.

Regards,
Barney


liorean wrote:
> On 13/08/07, Barney Carroll <barney at textmatters.com> wrote:
>> How do I go about adding classes to elements in JS? I thought it would
>> be dirt simple but my initial fumbles and google searches are churning
>> up much...
> 
> To replace the current set of classes on the element, use
> 
>     elm.className='blah';
> 
> To add a class, use
> 
>     elm.className+=' blah';
> 
> To remove a class, I'd use
> 
>     elm.className=elm.className.replace(/\bblah\b/,'');
> 
> Of course, if you're doing many class changes on an element, you might
> want to amend that code with something that won't leave lots of
> whitespace around.



More information about the Javascript mailing list