Remove CSS class from element with JavaScript (no jQuery)

JavascriptHtmlCss

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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');
  if (el.classList.contains("red")) {
    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

Solution 2 - Javascript

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|$)'), ' ');

Solution 3 - Javascript

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;
}

Solution 4 - Javascript

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,' ');
  }
}

Solution 5 - Javascript

div.classList.add("foo");
div.classList.remove("foo");

More at https://developer.mozilla.org/en-US/docs/Web/API/element.classList

Solution 6 - Javascript

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");

Solution 7 - Javascript

It's very simple, I think.

document.getElementById("whatever").classList.remove("className");

Solution 8 - Javascript

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;
}

Solution 9 - Javascript

var element = document.getElementById('example_id');
var remove_class = 'example_class';

element.className = element.className.replace(' ' + remove_class, '').replace(remove_class, '');

Solution 10 - Javascript

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="";

Solution 11 - Javascript

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

With the plus sign ('+') appending the class as opposed to overwriting any existing classes

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmraView Question on Stackoverflow
Solution 1 - JavascriptPaul RougetView Answer on Stackoverflow
Solution 2 - JavascriptЯegDwightView Answer on Stackoverflow
Solution 3 - JavascriptMatthewView Answer on Stackoverflow
Solution 4 - JavascriptKeith RousseauView Answer on Stackoverflow
Solution 5 - JavascriptjoseconstelaView Answer on Stackoverflow
Solution 6 - JavascriptDuncanView Answer on Stackoverflow
Solution 7 - JavascriptLivinKalaiView Answer on Stackoverflow
Solution 8 - JavascriptscunliffeView Answer on Stackoverflow
Solution 9 - JavascriptTornikeView Answer on Stackoverflow
Solution 10 - JavascriptAmirView Answer on Stackoverflow
Solution 11 - JavascriptlesView Answer on Stackoverflow