2

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&deg;C increase</button>
    <button class="btn" onclick="updateChart(data2c)"> 2&deg;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";
    })
})
  • 1
    The difference here is how `this` is binded in `function()` and the lexical `() =>`. `console.log(this)` to see the differences – Sterling Archer Feb 20 '20 at 15:51
  • 1
    The arrow functions doesn't have their own `this` instead they use lexical `this`. I think changing `() =>` to `function` will solve the problem – Maheer Ali Feb 20 '20 at 15:53
  • 1
    A better way to remove or add class is to use `element.classList.add` and `element.classList.add` – Maheer Ali Feb 20 '20 at 15:54
  • 1
    Also to add to the above tips, you can use a `for ... of` loop in ES6 as well, instead of the `forEach` – Deep Frozen Feb 20 '20 at 15:54

0 Answers0