[Javascript] Adding classes

liorean liorean at gmail.com
Mon Aug 13 07:33:29 CDT 2007


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.
-- 
David "liorean" Andersson



More information about the Javascript mailing list