« 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

No Comments Here. Add yours below!

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

Comments

So all he had to do was learn some Norse magic.  Free Loki.  Find Liz.  Stop Ragnarok.  Help Sygin get her revenge on the lords of the Æsir.  Defeat the Krim, and get home.
Easy, really.
Jerry, Pyramid Power, Eric Flint & Dave Freer