So I have 30 buttons (id="button1" to "button30"):
<button type="button" class="buttons" id="button1">1</button>
and I set up some JS so that the button changes colors on every click:
let index = 0;
const colors = ['green', 'red', '#405cf5'];
let btn = document.querySelector('#button1');
document.querySelector('#button1').addEventListener('click', function(){
btn.style.backgroundColor = colors[index];
index = index >= colors.length - 1 ? 0 : index + 1;
})
I'm not sure how to set this up so that all my buttons do this without copy and pasting and manually typing out the ID each time.
.querySelectorAll()+ a property they all have in common (e.g. they are buttons, the classbuttons, the id starts withbutton, ...) +thisanddata-*attributes. Also you might want to have a look at the modulus operator%button1->green, second click onbutton1->red. What will be the color ofbutton2if we now click that for the first time?greenorred?