Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove CSS class from element with JavaScript (no jQuery) [duplicate]

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.

like image 362
Amra Avatar asked Jan 28 '10 15:01

Amra


2 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');    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

like image 116
Paul Rouget Avatar answered Oct 11 '22 22:10

Paul Rouget


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|$)'), ' '); 
like image 32
ЯegDwight Avatar answered Oct 11 '22 23:10

ЯegDwight