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.
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.
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,' ');
}
}
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;
}
Hey Cesar,
Check this out: http://stackoverflow.com/questions/195951/change-an-elements-css-class-with-javascript
This answer has some good examples.
Patrick.
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.
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";
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