Could anyone let me know how to remove a class on an element using JavaScript only? Please do not give me an answer with jQuery as I can't use it, and I don't know anything about it.
11 Answers
The right and standard way to do it is using classList
. It is now widely supported in the latest version of most modern browsers:
ELEMENT.classList.remove("CLASS_NAME");
remove.onclick = () => {
const el = document.querySelector('#el');
el.classList.remove("red");
}
.red {
background: red
}
<div id='el' class="red"> Test</div>
<button id='remove'>Remove Class</button>
Documentation: https://developer.mozilla.org/en/DOM/element.classList
-
6Very nice! That is so much simpler than regular expressions and splitting
className
into parts and manually traversing them.Victor Zamanian– Victor Zamanian02/12/2013 23:16:44Commented Feb 12, 2013 at 23:16 -
25@dzhioev - I believe because it is relatively new and not supported in older browsers (IE support starts at IE10)Tom Pietrosanti– Tom Pietrosanti04/05/2013 13:58:02Commented Apr 5, 2013 at 13:58
-
11On the MDN page there is a shim provided for older browsers.oxygen– oxygen06/07/2013 16:52:22Commented Jun 7, 2013 at 16:52
-
5ELEMENT.classList has both 'add' and 'remove', btw.Kamilius– Kamilius10/30/2014 11:57:08Commented Oct 30, 2014 at 11:57
-
3Why bother checking if the class is there before calling
.remove
if the function doesn't throw any errors if the class isn't there? If you remove the if statement, then JavaScript doesn't have to scan through the class list twice every time it is true.apokaliptis– apokaliptis05/14/2021 10:47:09Commented May 14, 2021 at 10:47
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.
UPDATE: To support class names containing dash character, such as "My-Class", use
document.getElementById("MyID").className =
document.getElementById("MyID").className
.replace(new RegExp('(?:^|\\s)'+ 'My-Class' + '(?:\\s|$)'), ' ');
-
13Correct me if I'm wrong but I think that your 1st argument on
replace
must be a regex, so without enclosing it in quotes:.replace(/\bMyClass\b/,'')
. But then 'MyClass' must to be a literal, otherwise maybe creating the regex dinamically could work:.replace(new RegExp('\\b' + myClass + '\\b'),'')
Pau Fracés– Pau Fracés01/08/2013 12:12:35Commented Jan 8, 2013 at 12:12 -
3@PauFracés Check the edit history. The inconsistency got introduced by someone else.ЯegDwight– ЯegDwight01/08/2013 12:20:01Commented Jan 8, 2013 at 12:20
-
55The use of the word boundary metacharacter
\b
is not suitable here, because the word boundary occurs also between a word character[A-Za-z0-9_]
and the dash-
character. Therefore a class name e.g. 'different-MyClass' would also be replaced, resulting in 'different-'. There is a better solution which matches whitespace characters around the class name.Adam– Adam06/03/2013 15:53:45Commented Jun 3, 2013 at 15:53 -
2I'm also removing a space if its there:
domNode.className.replace(new RegExp(" ?\\b"+cssClass+"\\b"),'')
B T– B T05/15/2014 07:16:07Commented May 15, 2014 at 7:16 -
1ill just copy paste this here since this where google leads me to not the page with right answer linked in Adam comment.
function removeClass(e,c) {e.className = e.className.replace( new RegExp('(?:^|\\s)'+c+'(?!\\S)') ,'');}
Muhammad Umer– Muhammad Umer06/28/2015 17:25:49Commented Jun 28, 2015 at 17:25
Here's a way to bake this functionality right into all DOM elements:
HTMLElement.prototype.removeClass = function(remove) {
var newClassName = "";
var i;
var classes = this.className.split(" ");
for(i = 0; i < classes.length; i++) {
if(classes[i] !== remove) {
newClassName += classes[i] + " ";
}
}
this.className = newClassName;
}
-
3Very elegant and most applicable to the question.Alex Beynenson– Alex Beynenson12/03/2012 15:07:47Commented Dec 3, 2012 at 15:07
-
7Add an if wrapper [if (typeof HTMLElement.prototype.removeClass !== "function") {] to make this answer most elegant in case browsers add support for removeClass in the future..Matthieu Cormier– Matthieu Cormier01/16/2013 14:43:29Commented Jan 16, 2013 at 14:43
-
@Matthew A logoical programmatic way. Appreciate it. Looks cross-browser too. Is it???Rajesh Paul– Rajesh Paul10/05/2013 07:17:48Commented Oct 5, 2013 at 7:17
-
1You can also split classes by \t \n \r and \s+, your split-nonregex doesn't take that into account.Stefan Steiger– Stefan Steiger12/01/2014 21:20:05Commented Dec 1, 2014 at 21:20
-
3Add a trim() at the end of return to remove redundant spaces when function is used more then once (such as toggling an active/deactivate state).Sam– Sam11/20/2015 21:26:35Commented Nov 20, 2015 at 21:26
div.classList.add("foo");
div.classList.remove("foo");
More at https://developer.mozilla.org/en-US/docs/Web/API/element.classList
-
7Nice, too bad supports starts with IE 10 and Android 3. Why they didn't code this stuff 10 years ago?..andreszs– andreszs08/02/2014 23:09:58Commented Aug 2, 2014 at 23:09
-
2@Andrew To be honest the entire world of web technologies looks like a big pile of ideas thrown together without system or consistency...Nearoo– Nearoo02/05/2017 00:53:01Commented Feb 5, 2017 at 0:53
Try this:
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,' ');
}
}
-
2
el.className.replace(/(\s|^)someclass(\s|$)/, ' ')
If you aren't feeling like creating a helper function. :)Celmaun– Celmaun01/14/2015 07:33:35Commented Jan 14, 2015 at 7:33 -
Why \\s, and not just \s ? Wondering.Anthony Rutledge– Anthony Rutledge11/07/2015 09:47:49Commented Nov 7, 2015 at 9:47
-
1You need to escape the backslashKeith Rousseau– Keith Rousseau11/08/2015 02:51:14Commented Nov 8, 2015 at 2:51
Edit
Okay, complete re-write. It's been a while, I've learned a bit and the comments have helped.
Node.prototype.hasClass = function (className) {
if (this.classList) {
return this.classList.contains(className);
} else {
return (-1 < this.className.indexOf(className));
}
};
Node.prototype.addClass = function (className) {
if (this.classList) {
this.classList.add(className);
} else if (!this.hasClass(className)) {
var classes = this.className.split(" ");
classes.push(className);
this.className = classes.join(" ");
}
return this;
};
Node.prototype.removeClass = function (className) {
if (this.classList) {
this.classList.remove(className);
} else {
var classes = this.className.split(" ");
classes.splice(classes.indexOf(className), 1);
this.className = classes.join(" ");
}
return this;
};
Old Post
I was just working with something like this. Here's a solution I came up with...
// Some browsers don't have a native trim() function
if(!String.prototype.trim) {
Object.defineProperty(String.prototype,'trim', {
value: function() {
return this.replace(/^\s+|\s+$/g,'');
},
writable:false,
enumerable:false,
configurable:false
});
}
// addClass()
// first checks if the class name already exists, if not, it adds the class.
Object.defineProperty(Node.prototype,'addClass', {
value: function(c) {
if(this.className.indexOf(c)<0) {
this.className=this.className+=' '+c;
}
return this;
},
writable:false,
enumerable:false,
configurable:false
});
// removeClass()
// removes the class and cleans up the className value by changing double
// spacing to single spacing and trimming any leading or trailing spaces
Object.defineProperty(Node.prototype,'removeClass', {
value: function(c) {
this.className=this.className.replace(c,'').replace(' ',' ').trim();
return this;
},
writable:false,
enumerable:false,
configurable:false
});
Now you can call myElement.removeClass('myClass')
or chain it: myElement.removeClass("oldClass").addClass("newClass");
-
3I'm very late here, but I have an example case where this would not work: Consider an element that has classes testClass and testClass2. (class="testClass testClass2") We wish to remove testClass from the element. Result using your method: class="2" This is why breaking it into an array is favourable. Of course, it is still possible to achieve the correct result using pure string manipulation, but it becomes more complex. If you don't want a mess of code you'll need to use Regex. The advantage of using an array is that the code is easily readable.Yoshi Walsh– Yoshi Walsh05/15/2014 02:06:15Commented May 15, 2014 at 2:06
-
@YM_Industries You're right! I'll edit my post.Duncan– Duncan05/16/2014 20:01:50Commented May 16, 2014 at 20:01
-
@Knu Native
Element.classList.add()
doesn't support the space in"one two"
.Duncan– Duncan03/06/2015 11:05:05Commented Mar 6, 2015 at 11:05 -
@Knu What about
".one.two"
,("one", "two", ...)
,["one","two"]
,{"0":"one","1":"two"}
... etc. I'll leave non-standard parameter handling to the person implementing their code. :)Duncan– Duncan03/06/2015 18:41:12Commented Mar 6, 2015 at 18:41 -
classList
isn't supported in IE < 11. You can use regex instead :this.className = this.className.replace(new RegExp('(?:^|\\s)' + className + '(?:\\s|$)'), '').trim();
Flox– Flox05/10/2017 08:02:47Commented May 10, 2017 at 8:02
It's very simple, I think.
document.getElementById("whatever").classList.remove("className");
-
8This has poor cross-browser support. Internet Explorer doesn't support it in any version prior to 10. developer.mozilla.org/en-US/docs/Web/API/…Justin Morgan– Justin Morgan08/26/2013 20:58:46Commented Aug 26, 2013 at 20:58
-
3This to me seems like the right answer. If you are worried about cross browser use a polyfill. github.com/eligrey/classList.jsShannon Poole– Shannon Poole08/28/2013 16:28:36Commented Aug 28, 2013 at 16:28
-
3@ShannonPoole Sometimes you just need to do a simple task in an IE8-compatible way and you don't want it to depend on library support or a heavy polyfill.acjay– acjay02/19/2015 12:53:49Commented Feb 19, 2015 at 12:53
-
3@acjay and sometimes you throw caution to the wind and just follow the modern standard :)Shannon Poole– Shannon Poole02/20/2015 10:13:04Commented Feb 20, 2015 at 10:13
-
1To support IE, you can use regex instead :
this.className = this.className.replace(new RegExp('(?:^|\\s)' + className + '(?:\\s|$)'), '').trim();
Flox– Flox05/10/2017 08:04:57Commented May 10, 2017 at 8:04
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;
}
var element = document.getElementById('example_id');
var remove_class = 'example_class';
element.className = element.className.replace(' ' + remove_class, '').replace(remove_class, '');
I use this JS snippet code :
First of all, I reach all the classes then according to index of my target class, I set className = "".
Target = document.getElementsByClassName("yourClass")[1];
Target.className="";
-
5This is not a good solution because it will remove all classes from the element.dzimney– dzimney08/11/2017 19:09:43Commented Aug 11, 2017 at 19:09
document.getElementById("whatever").className += "classToKeep";
With the plus sign ('+') appending the class as opposed to overwriting any existing classes
document.getElementById("theID").removeAttribute("class")