I am facing an issue with my website where I have buttons on the right side. I want to use JavaScript to change the style of the button when it is clicked.
When the page loads, the home button should have a background-color: green
. However, when another button is clicked, the home button's background-color
should change to black/gray. The button that was clicked should remain black/gray, and there should be no error in the console. But, if you click any other button after the first click, the background-color
will stay gray/black and an error will appear in the console:
app.js:12 Uncaught TypeError: Cannot read properties of undefined (reading 'className') at HTMLDivElement.<anonymous> (app.js:12:53)
The following code is being used:
const sections = document.querySelectorAll('.section');
const sectBtns = document.querySelectorAll('.controls');
const sectBtn = document.querySelectorAll('.control');
const allSection = document.querySelector('.main-content');
function PageTransitions() {
// Button click active 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';
})
}
}
PageTransitions();
This issue prevents the background color from changing. Any suggestions on how to resolve this would be greatly appreciated. Thank you!