I want to remove and add an active class on selected button.
My buttons:
<div id="myBtnDiv">
<button class="btn active" onclick="updateChart(data15c)">1.5°C increase</button>
<button class="btn" onclick="updateChart(data2c)"> 2°C increase</button>
</div>
My working old code:
let getBtnDiv = document.getElementById("myBtnDiv")
let btns = getBtnDiv.querySelectorAll('.btn');
for (let i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function(){
let currentBtn = document.getElementsByClassName("active");
currentBtn[0].className = currentBtn[0].className.replace(" active", "")
this.className += " active";
})
}
My new code switches from a for loop to forEach and uses ES6 syntax. I'm not sure what the issue is here because when I use function() {} instead of () => {} it runs just fine.
btns.forEach(btn => {
btn.addEventListener('click', () => {
let current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
})
})