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?
CodePudding user response:
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');
CodePudding user response:
Probably document.querySelectorAll('.active-btn');
returns empty array, because of that your currentBtn
is empty and currentBtn[0]
is undefined
.
This causes currentBtn[0].className
to fail