§ 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
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
Categories
Comments
- Walid on "Adventures with Ubuntu 9.10 on G4 Yikes!" - I am in the same process as you. Although I still dual-boot to Windows for my ganimg leisure. My first contact with Ubuntu was way…
- Slashback on "Simpler adding & removing element classnames" - Actually, the addClassName function does what you want, pretty much the same way you suggest.
- angie on "Simpler adding & removing element classnames" - 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…
- backlinks on "Adjust iframe height to contents" - Definitely helped me.
- Slashback on "Simpler validate form fields are filled in (no additional class names)" - You are welcome!
Slashback says:
Actually, the addClassName function does what you want, pretty much the same way you suggest.
July 26th, 2012 at 7:36 AM