I’m referring to example
// Get the container element
var btnContainer = document.getElementById("myDIV");
// Get all buttons with class="btn" inside the container
var btns = btnContainer.getElementsByClassName("btn");
// Loop through the buttons and add the 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";
});
}.btn {
border: none;
outline: none;
padding: 10px 16px;
background-color: #f1f1f1;
cursor: pointer;
}
/* Style the active class (and buttons on mouse-over) */
.active, .btn:hover {
background-color: #666;
color: white;
}<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>
In this to replace active class to nil, current[0].className is used as below
current[0].className = current[0].className.replace(" active", "");
But to add classname, this keyword is used
this.className += " active";
Why can’t I add new classname as below
current[0].className += " active"; ?
Advertisement
Answer
Because this in your current context is the clicked button. Another way to do it is with e.target.classList.add('active');, but before doing so you should pass e to the callback function parameter like that
btns[i].addEventListener("click", function(e) {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
e.target.classList.add('active');
});