I'm looking for a fast and secure way to add and remove classes from an html element without jQuery.
It also should be working in early IE (IE8 and up).

- 25,161
- 11
- 89
- 121

- 1,081
- 2
- 8
- 14
-
2Define *'early'*? See the [`classList` shim on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element.classList#wrapper) For IE>7 – George Nov 04 '14 at 13:42
13 Answers
Another approach to add the class to element using pure JavaScript
For adding class:
document.getElementById("div1").classList.add("classToBeAdded");
For removing class:
document.getElementById("div1").classList.remove("classToBeRemoved");
Note: but not supported in IE <= 9 or Safari <=5.0

- 8,665
- 12
- 47
- 70
-
2Note: "[*(I) guess (in) IE 8 and up.*](http://stackoverflow.com/questions/26736587/how-to-add-and-remove-classes-in-js-without-jquery#comment42059466_26736587)" – David Thomas Nov 04 '14 at 13:49
-
1
-
1@edddd yes! try element.classList.toggle, examples on [MDN ClassList](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList) – Jeff Spicoli Dec 08 '22 at 19:09
The following 3 functions work in browsers which don't support classList
:
function hasClass(el, className)
{
if (el.classList)
return el.classList.contains(className);
return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'));
}
function addClass(el, className)
{
if (el.classList)
el.classList.add(className)
else if (!hasClass(el, className))
el.className += " " + className;
}
function removeClass(el, className)
{
if (el.classList)
el.classList.remove(className)
else if (hasClass(el, className))
{
var reg = new RegExp('(\\s|^)' + className + '(\\s|$)');
el.className = el.className.replace(reg, ' ');
}
}
https://jaketrent.com/post/addremove-classes-raw-javascript/

- 7,242
- 3
- 52
- 70
-
I always wonder why people add functionality for modern browsers? I mean isn't that code redundant if you want to support older browsers? – Goowik May 22 '19 at 18:42
-
jongo45's answer is the best. [ANSWER](https://stackoverflow.com/a/26736737/2968762) – Abhi Jul 19 '19 at 10:48
-
1@Abhi no it's not. His solution is for `IE10 onwards` and the questions states `IE8 and up`. – Dan Bray Jul 19 '19 at 15:17
For future friendliness, I second the recommendation for classList with polyfill/shim: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#wrapper
var elem = document.getElementById( 'some-id' );
elem.classList.add('some-class'); // Add class
elem.classList.remove('some-other-class'); // Remove class
elem.classList.toggle('some-other-class'); // Add or remove class
if ( elem.classList.contains('some-third-class') ) { // Check for class
console.log('yep!');
}

- 1,892
- 4
- 26
- 34
I'm baffled none of the answers here prominently mentions the incredibly useful DOMTokenList.prototype.toggle
method, which really simplifies alot of code.
E.g. you often see code that does this:
if (element.classList.contains(className) {
element.classList.remove(className)
} else {
element.classList.add(className)
}
This can be replaced with a simple call to
element.classList.toggle(className)
What is also very helpful in many situations, if you are adding or removing a class name based on a condition, you can pass that condition as a second argument. If that argument is truthy, toggle
acts as add
, if it's falsy, it acts as though you called remove
.
element.classList.toggle(className, condition) // add if condition truthy, otherwise remove

- 53,704
- 14
- 91
- 128
To add class without JQuery just append yourClassName
to your element className
document.documentElement.className += " yourClassName";
To remove class you can use replace()
function
document.documentElement.className.replace(/(?:^|\s)yourClassName(?!\S)/,'');
Also as @DavidThomas mentioned you'd need to use the new RegExp()
constructor if you want to pass class names dynamically to the replace function.

- 10,351
- 4
- 44
- 67
-
@George easely fixable by adding a space before and after className – Alexandru Severin Nov 04 '14 at 13:50
-
@George In regular expressions, \b anchors the regex at a word boundary or the position between a word and a non-word character, or vice versa. – zavg Nov 04 '14 at 13:52
-
1Note that you'd need to use the `new RegExp()` constructor if you want to pass class-names dynamically. – David Thomas Nov 04 '14 at 13:54
-
@DavidThomas Thanks for the remark, I include it in the answer if you don't mind – zavg Nov 04 '14 at 13:56
-
`\b` isn't sufficient in a RegExp because there are boundary characters that are valid in a class name. `/\bfoo\b/` will replace the first part of a class `"foo-bar"`. – Nov 04 '14 at 14:27
-
@squint yes, you are right, it seems that it is necessary to use more complex regexp to deal with these cases... – zavg Nov 04 '14 at 14:32
Add & Remove Classes (tested on IE8+)
Add trim() to IE (taken from: .trim() in JavaScript not working in IE)
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
Add and Remove Classes:
function addClass(element,className) {
var currentClassName = element.getAttribute("class");
if (typeof currentClassName!== "undefined" && currentClassName) {
element.setAttribute("class",currentClassName + " "+ className);
}
else {
element.setAttribute("class",className);
}
}
function removeClass(element,className) {
var currentClassName = element.getAttribute("class");
if (typeof currentClassName!== "undefined" && currentClassName) {
var class2RemoveIndex = currentClassName.indexOf(className);
if (class2RemoveIndex != -1) {
var class2Remove = currentClassName.substr(class2RemoveIndex, className.length);
var updatedClassName = currentClassName.replace(class2Remove,"").trim();
element.setAttribute("class",updatedClassName);
}
}
else {
element.removeAttribute("class");
}
}
Usage:
var targetElement = document.getElementById("myElement");
addClass(targetElement,"someClass");
removeClass(targetElement,"someClass");
A working JSFIDDLE: http://jsfiddle.net/fixit/bac2vuzh/1/

- 1
- 1

- 1,959
- 18
- 19
-
when i add the test class this happens:then i remove the class– Peter Eberle Nov 04 '14 at 15:31it deletes the "r" in parent-container
-
Added a working JSFIDDLE - if it keeps happening, let me know on which browser & version – Yonatan Ayalon Nov 04 '14 at 16:48
Try this:
const element = document.querySelector('#elementId');
if (element.classList.contains("classToBeRemoved")) {
element.classList.remove("classToBeRemoved");
}

- 10,136
- 1
- 57
- 42
You can also do
elem.classList[test ? 'add' : 'remove']('class-to-add-or-remove');
Instead of
if (test) {
elem.classList.add('class-to-add-or-remove');
} else {
elem.classList.remove('class-to-add-or-remove');
}

- 842
- 9
- 16
I'm using this simple code for this task:
CSS Code
.demo {
background: tomato;
color: white;
}
Javascript code
function myFunction() {
/* Assign element to x variable by id */
var x = document.getElementById('para);
if (x.hasAttribute('class') {
x.removeAttribute('class');
} else {
x.setAttribute('class', 'demo');
}
}

- 3,161
- 6
- 25
- 40

- 21
- 1
Updated JS Class Method
The add
methods do not add duplicate classes and the remove
method only removes class with exact string match.
const addClass = (selector, classList) => {
const element = document.querySelector(selector);
const classes = classList.split(' ')
classes.forEach((item, id) => {
element.classList.add(item)
})
}
const removeClass = (selector, classList) => {
const element = document.querySelector(selector);
const classes = classList.split(' ')
classes.forEach((item, id) => {
element.classList.remove(item)
})
}
addClass('button.submit', 'text-white color-blue') // add text-white and color-blue classes
removeClass('#home .paragraph', 'text-red bold') // removes text-red and bold classes

- 912
- 7
- 25
When you remove RegExp from the equation you leave a less "friendly" code, but it still can be done with the (much) less elegant way of split().
function removeClass(classString, toRemove) {
classes = classString.split(' ');
var out = Array();
for (var i=0; i<classes.length; i++) {
if (classes[i].length == 0) // double spaces can create empty elements
continue;
if (classes[i] == toRemove) // don't include this one
continue;
out.push(classes[i])
}
return out.join(' ');
}
This method is a lot bigger than a simple replace() but at least it can be used on older browsers. And in case the browser doesn't even support the split() command it's relatively easy to add it using prototype.

- 1,794
- 1
- 12
- 18
Just in case someone needs to toggle class on click and remove on other elements in JS only. You can try to do following :
var accordionIcon = document.querySelectorAll('.accordion-toggle');
//add only on first element, that was required in my case
accordionIcon[0].classList.add('close');
for (i = 0; i < accordionIcon.length; i++) {
accordionIcon[i].addEventListener("click", function(event) {
for (i = 0; i < accordionIcon.length; i++) {
if(accordionIcon[i] !== event.target){
accordionIcon[i].classList.remove('close');
}
event.target.classList.toggle("close");
}
})
}

- 31
- 1
- 6