Bagaimana untuk menambahkan kelas 'active' kepada elemen semasa

Belajar bagaimana untuk menambahkan kelas 'active' kepada elemen semasa menggunakan JavaScript.

Tunjukkan butang aktif/semasa (dipaksa):

亲自试一试

Active element

First step - Add 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>

Second step - Add CSS:

/* Set button styles */
.btn {
  border: none;
  outline: none;
  padding: 10px 16px;
  background-color: #f1f1f1;
  cursor: pointer;
}
/* Set styles for 'active' class (and button when hovered) */
.active, .btn:hover {
  background-color: #666;
  color: white;
}

Third step - Add JavaScript:

// Get the container element
var btnContainer = document.getElementById("myDIV");
// Get all buttons with class="btn" inside the container
var btns = btnContainer.getElementsByClassName("btn");
// Traverse buttons and add 'active' class to the current/clicked button
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";
  });
}

亲自试一试

If the button element does not have the 'active' class set initially, please use the following code:

// Get the container element
var btnContainer = document.getElementById("myDIV");
// Get all buttons with class="btn" inside the container
var btns = btnContainer.getElementsByClassName("btn");
// Traverse buttons and add 'active' class to the current/clicked button
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    var current = document.getElementsByClassName("active");
    // If there is no 'active' class
    if (current.length > 0) {
      current[0].className = current[0].className.replace(" active", "");
    }
    // Add 'active' class to the current/clicked button
    this.className += " active";
  });
}

亲自试一试