I’m referring to example
JavaScript
x
14
14
1
// Get the container element
2
var btnContainer = document.getElementById("myDIV");
3
4
// Get all buttons with class="btn" inside the container
5
var btns = btnContainer.getElementsByClassName("btn");
6
7
// Loop through the buttons and add the active class to the current/clicked button
8
for (var i = 0; i < btns.length; i++) {
9
btns[i].addEventListener("click", function() {
10
var current = document.getElementsByClassName("active");
11
current[0].className = current[0].className.replace(" active", "");
12
this.className += " active";
13
});
14
}
JavaScript
1
13
13
1
.btn {
2
border: none;
3
outline: none;
4
padding: 10px 16px;
5
background-color: #f1f1f1;
6
cursor: pointer;
7
}
8
9
/* Style the active class (and buttons on mouse-over) */
10
.active, .btn:hover {
11
background-color: #666;
12
color: white;
13
}
JavaScript
1
7
1
<div id="myDIV">
2
<button class="btn">1</button>
3
<button class="btn active">2</button>
4
<button class="btn">3</button>
5
<button class="btn">4</button>
6
<button class="btn">5</button>
7
</div>
In this to replace active class to nil, current[0].className
is used as below
JavaScript
1
2
1
current[0].className = current[0].className.replace(" active", "");
2
But to add classname, this
keyword is used
JavaScript
1
2
1
this.className += " active";
2
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
JavaScript
1
6
1
btns[i].addEventListener("click", function(e) {
2
var current = document.getElementsByClassName("active");
3
current[0].className = current[0].className.replace(" active", "");
4
e.target.classList.add('active');
5
});
6