Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I toggle an element's class in pure JavaScript?

2014 answer: classList.toggle() is the standard and supported by most browsers.

Older browsers can use use classlist.js for classList.toggle():

var menu = document.querySelector('.menu') // Using a class instead, see note below.
menu.classList.toggle('hidden-phone');

As an aside, you shouldn't be using IDs (they leak globals into the JS window object).


Here is solution implemented with ES6

const toggleClass = (el, className) => el.classList.toggle(className);

usage example

toggleClass(document.querySelector('div.active'), 'active'); // The div container will not have the 'active' class anymore

Take a look at this example: JS Fiddle

function toggleClass(element, className){
    if (!element || !className){
        return;
    }

    var classString = element.className, nameIndex = classString.indexOf(className);
    if (nameIndex == -1) {
        classString += ' ' + className;
    }
    else {
        classString = classString.substr(0, nameIndex) + classString.substr(nameIndex+className.length);
    }
    element.className = classString;
}

This one works in earlier versions of IE also.

function toogleClass(ele, class1) {
  var classes = ele.className;
  var regex = new RegExp('\\b' + class1 + '\\b');
  var hasOne = classes.match(regex);
  class1 = class1.replace(/\s+/g, '');
  if (hasOne)
    ele.className = classes.replace(regex, '');
  else
    ele.className = classes + class1;
}
.red {
  background-color: red
}
div {
  width: 100px;
  height: 100px;
  margin-bottom: 10px;
  border: 1px solid black;
}
<div class="does red redAnother " onclick="toogleClass(this, 'red')"></div>

<div class="does collapse navbar-collapse " onclick="toogleClass(this, 'red')"></div>

don't need regex just use classlist

var id=document.getElementById('myButton');


function toggle(el,classname){
if(el.classList.contains(classname)){
el.classList.remove(classname)
}
else{
el.classList.add(classname)
}
}




id.addEventListener('click',(e)=>{

toggle(e.target,'red')
})
.red{

background:red

}
<button id="myButton">Switch</button>

Simple Usage above Example

var id=document.getElementById('myButton');


function toggle(el,classname){
el.classList.toggle(classname)
}




id.addEventListener('click',(e)=>{

toggle(e.target,'red')
})
.red{

background:red

}
<button id="myButton">Switch</button>