What you can do is use querySelector to grab the current "clicked" element, remove the class, and then add the class to the clicked element.
var btn = document.getElementsByClassName("btn"); for (var i = 0; i < btn.length; i++) { btn[i].addEventListener("click", myFunction); } function myFunction() { var parentElement = this.parentElement; var previousElement = document.querySelector('.clicked'); if (previousElement) { previousElement.classList.remove('clicked'); } if (this.classList.length <= 2) { this.classList.add("clicked"); } else { this.classList.remove("clicked"); } } .clicked { color: pink; } <div> <button class="btn-color-black btn">Yo!</button> <button class="btn-color-black btn">Yo!</button> <button class="btn-color-black btn">Yo!</button> </div> What you can do is use querySelector to grab the current "clicked" element, remove the class, and then add the class to the clicked element.
var btn = document.getElementsByClassName("btn"); for (var i = 0; i < btn.length; i++) { btn[i].addEventListener("click", myFunction); } function myFunction() { var parentElement = this.parentElement; var previousElement = document.querySelector('.clicked'); if (previousElement) { previousElement.classList.remove('clicked'); } if (this.classList.length <= 2) { this.classList.add("clicked"); } else { this.classList.remove("clicked"); } }