I have a list of buttons.
I need to add a clickEvent to each of them, when clicked it needs to check if there's another button with the class(btnActive), remove it and add the class to the clicked button.
document.querySelectorAll('.btn').forEach(function(el) {
el.addEventListener('click', function(e) {
let i = 0;
for (i = 0; i < btnAll.length; i++) {
if (i.classList.contains('btnActive')) {
i.classList.remove('btnActive');
}
}
el.classList.add('btnActive');
});
});
<div class="btnContainer">
<div class="btn">
<span class="btnActive">
0
</span>
</div>
<div class="btn">
<span>
1
</span>
</div>
<div class="btn">
<span>
2
</span>
</div>
<div class="btn">
<span>
3
</span>
</div>
</div>
I have that little JS block and I can't seem to get it to work
Since the other answers have covered why your code doesn't work, here's an example where you attach one event listener to the container and catch events that bubble up from the other elements (see: event propagation). It makes for more practical code.
// Get the container and the buttons
const container = document.querySelector('.btnContainer');
const buttons = document.querySelectorAll('.btn');
// Add a click listener to the container
container.addEventListener('click', handleClick, false);
function handleClick(e) {
const { target } = e;
// If a button has been clicked
if (target.classList.contains('btn')) {
// Clear any active buttons
buttons.forEach(button => button.classList.remove('btnActive'));
// Make the clicked button active
target.classList.add('btnActive');
}
}
.btnActive {
background-color: red;
}
<div class="btnContainer">
<button class="btn btnActive">0</button>
<button class="btn">1</button>
<button class="btn">2</button>
<button class="btn">3</button>
</div>