Remove CSS class from element with JavaScript (no jQuery) [duplicate]
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
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|$)'), ' ');
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;}