How to add the active class to the current element
- Página anterior Alterar classe
- Próxima página Visão em árvore
Learn how to use JavaScript to add the active class to the current element.
Highlight the active/current (pressed) button:
Elemento ativo
Primeiro passo - Adicionar HTML:
<div id="myDIV"> <button class="btn">1</button> <button class="btn active">2</button> <button class="btn">3</button> <button class="btn">4</button> <button class="btn">5</button> </div>
Segundo passo - Adicionar CSS:
/* Definir estilos do botão */ .btn { borda: none; contorno: none; margem: 10px 16px; cor-de-fundo: #f1f1f1; cursor: ponteiro; } /* Definir estilos para a classe 'active' (e para o botão ao passar o mouse) */ .active, .btn:hover { cor-de-fundo: #666; cor: branco; }
Terceiro passo - Adicionar JavaScript:
// Obter o elemento do contêiner var btnContainer = document.getElementById("myDIV"); // Obter todos os botões com a classe 'btn' dentro do contêiner var btns = btnContainer.getElementsByClassName("btn"); // Percorrer os botões e adicionar a classe 'active' ao botão atual/clicado for (var i = 0; i < btns.length; i++) { btns[i].addEventListener("click", function() { var current = document.getElementsByClassName("active"); current[0].className = current[0].className.replace(" active", ""); this.className += " active"; }); }
Se o elemento do botão não tiver a classe 'active' definida no início, use o seguinte código:
// Obter o elemento do contêiner var btnContainer = document.getElementById("myDIV"); // Obter todos os botões com a classe 'btn' dentro do contêiner var btns = btnContainer.getElementsByClassName("btn"); // Percorrer os botões e adicionar a classe 'active' ao botão atual/clicado for (var i = 0; i < btns.length; i++) { btns[i].addEventListener("click", function() { var current = document.getElementsByClassName("active"); // Se não houver a classe 'active' if (current.length > 0) { current[0].className = current[0].className.replace(" active", ""); } // Adicionar a classe 'active' ao botão atual/clicado this.className += " active"; }); }
- Página anterior Alterar classe
- Próxima página Visão em árvore