« Blog Home

§ Simpler adding & removing element classnames

Just use the javascript replace function...

The way I used to do this is just dumb; the replace function is quite straightforward and most likely faster.

 

function removeClassName(el, name) {
  el.className = el.className.replace(name, '');
}
function addClassName(el, name) {
  //don't waste time if it's already there
  if(el.className.indexOf(name)>-1)
    return;
  el.className += ' '+name;
}

//or, if you have reason to believe it's not already there, just
myelement.className+=' myclassname';

//swap known names
myelement.className = myelement.className.replace('oldName', 'newName');

last edited on May 7th, 2010 at 6:35 PM

Comments

Slashback says:

Actually, the addClassName function does what you want, pretty much the same way you suggest.

July 26th, 2012 at 7:36 AM

angie says:

And what if I want to add a class, but keeping the csseals the element already has?I mean, I have an element with a class, let's name it myClass1, and I want to add a secondary class, let's name it myClass2; to apply some effects dynamically.Is there any method to do it, or do i need to use something like:document.getElementById("blah").className = document.getElementById("blah").className+" myClass2"(I don't know if this workaround may work)thanks in advance!!

July 26th, 2012 at 6:42 AM

Add your comment

Name:
Email: (Will not be displayed - Privacy policy)
Website:
Comments:
  random image I can't read it!
Give me a different one!
Verify Post: Input the text from the image above to verify this post (helps prevent spam)
 

« Blog Home


“You make me feel like some kind’a space suit or somethin’,” Molly responded sorrowfully.
Molly, Run to Chaos Keep, Jack L. Chalker