Cómo agregar la clase 'active' al elemento actual

Aprende a usar JavaScript para agregar la clase 'active' al elemento actual.

Resaltar el botón activo/actual (ya presionado):

亲自试一试

Elemento activo

Primero - Añadir 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 - Añadir CSS:

/* Establecer estilos para los botones */
.btn {
  border: none;
  outline: none;
  padding: 10px 16px;
  background-color: #f1f1f1;
  cursor: pointer;
}
/* Establecer estilos para la clase 'active' (y el botón al pasar el ratón) */
.active, .btn:hover {
  background-color: #666;
  color: white;
}

Tercero - Añadir JavaScript:

// Obtener el elemento del contenedor
var btnContainer = document.getElementById("myDIV");
// Obtener todos los botones con class="btn" dentro del contenedor
var btns = btnContainer.getElementsByClassName("btn");
// Recorrer los botones y agregar la clase 'active' al botón actual/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";
  });
}

亲自试一试

Si el elemento button no tiene la clase 'active' desde el principio, use el siguiente código:

// Obtener el elemento del contenedor
var btnContainer = document.getElementById("myDIV");
// Obtener todos los botones con class="btn" dentro del contenedor
var btns = btnContainer.getElementsByClassName("btn");
// Recorrer los botones y agregar la clase 'active' al botón actual/clicado
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    var current = document.getElementsByClassName("active");
    // Si no hay clase 'active'
    if (current.length > 0) {
      current[0].className = current[0].className.replace(" active", "");
    }
    // Agregar la clase 'active' al botón actual/clicado
    this.className += " active";
  });
}

亲自试一试