views:

259

answers:

6

Could anyone let me know how to remove a class on a element using javascript only? Please do not give me the answer with jquery as I can't use it, and I dont know anything about it.

Thanks.

+4  A: 
function hasClass(ele,cls) {
    return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function removeClass(ele,cls) {
        if (hasClass(ele,cls)) {
            var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
            ele.className=ele.className.replace(reg,' ');
        }
    }
Keith Rousseau
+5  A: 

try:

function removeClassName(elem, name){
    var remClass = elem.className;
    var re = new RegExp('(^| )' + name + '( |$)');
    remClass = remClass.replace(re, '$1');
    remClass = remClass.replace(/ $/, '');
    elem.className = remClass;
}
scunliffe
+2  A: 

Hey Cesar,

Check this out: http://stackoverflow.com/questions/195951/change-an-elements-css-class-with-javascript

This answer has some good examples.

Patrick.

Patrick
A: 
document.getElementById("MyID").className =
    document.getElementById("MyID").className.replace(/\bMyClass\b/','');

where MyID is the ID of the element and MyClass is the name of the class you wish to remove.

RegDwight
+2  A: 

You could simply set the elements class to nothing.

document.getElementById("whatever").className = "";

or if you wanted to keep a particular class you could just reset the class

document.getElementById("whatever").className = "";
document.getElementById("whatever").className = "classToKeep";
TGuimond
Which removes **all** classes, not **a** class.
David Dorward
This only works if there is only 1 (one) class applied. If there is more than one, this wipes them all out.
scunliffe
Thank, I take this as answer due to simplicity. :-)
Cesar Lopez
@Cesar - Maybe you should have stated your requirements better. There is a difference between removing all classes and removing a class.
Keith Rousseau
A: 

Actually, the right way (standard) to do (but only works with Firefox3.6):

elt.classList.remove("class1");

I'm going to publish an article about that on http://hacks.mozilla.org next week with fallback mechanism for other browsers.

Documentation: https://developer.mozilla.org/en/DOM/element.classList

Paul Rouget