I want to turn this line that is jQuery into pure Javascript:
$('#menu #<? echo $idMenuAtivo; ?>').addClass('active');
How could I transform it?
I want to turn this line that is jQuery into pure Javascript:
$('#menu #<? echo $idMenuAtivo; ?>').addClass('active');
How could I transform it?
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
:
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();
}
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>