How to add a class in pure JavaScript?

2

I want to turn this line that is jQuery into pure Javascript:

$('#menu #<? echo $idMenuAtivo; ?>').addClass('active');

How could I transform it?

    
asked by anonymous 01.08.2017 / 22:51

3 answers

8

With "modern" browsers is enough:

document.querySelector('#menu #<? echo $idMenuAtivo; ?>').classList.add("active");

Or if you want to "toggle":

document.querySelector('#menu #<? echo $idMenuAtivo; ?>').classList.toggle("active");

Documentation:

Support for classList :

  • Chrome
  • Firefox
  • IE 10 +
  • Safari 5.1 +
01.08.2017 / 22:57
3

You could create your own addClass function, like this:

function addClass(element, classname){
    var currentClassList = (element.className || '').split(/\s+/);
    currentClassList
     .push(currentClassList.indexOf(classname) > -1 ? '' : classname);
    element.className = currentClassList.join(' ').trim();
}
    
01.08.2017 / 22:55
0

Here is an example of how to insert a class into javascript and remove it:

function addClass(id, classe) {
  var elemento = document.getElementById(id);
  var classes = elemento.className.split(' ');
  var getIndex = classes.indexOf(classe);

  if (getIndex === -1) {
    classes.push(classe);
    elemento.className = classes.join(' ');
  }
}

function delClass(id, classe) {
  var elemento = document.getElementById(id);
  var classes = elemento.className.split(' ');
  var getIndex = classes.indexOf(classe);

  if (getIndex > -1) {
    classes.splice(getIndex, 1);
  }
  elemento.className = classes.join(' ');
}
.active {
  color: blue
}
<button onClick="addClass('teste', 'active')">Adicionar classe</button>
<button onClick="delClass('teste', 'active')">Remover classe</button>

<div id="menu">
  <div id="teste">
    Olá!
  </div>
</div>
    
01.08.2017 / 23:01