Search code examples
javascripthtmlgoogle-chrome-extension

Get an error called Uncaught TypeError: Cannot read properties of undefined (reading 'className') className.replace property


I try create a website and i write a function. Whit This fuction Clicking on the icons will change the active icon class. But I get Cannot read properties of undefined (reading 'className') error. I have shared the function below. What do you think is the problem? This is my function;

function PageTransitions(){
    // Button click activa class
    for (let i = 0; i < sectBtn.length; i++){
        sectBtn[i].addEventListener('click', function(){
            let currentBtn = document.querySelectorAll('.active-btn');
            currentBtn[0].className = currentBtn[0].className.replace("active-btn", "")
            this.className += 'active-btn'
        }) 
    }
}

What do you think is the problem?


Solution

  • You have no button that is selected so you do not find one and it throws an error. So make sure the element exists before using it. And use classList

    const currentBtn = document.querySelector('.active-btn');
    if (currentBtn) currentBtn.classList.remove('active-btn');
    this.classList.add('active-btn');