Home > Software design >  For loop through different IDs with JS?
For loop through different IDs with JS?

Time:08-18

So I have 30 buttons (id="button1" to "button30"):

<button type="button"  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.

CodePudding user response:

Delegate, please.

Here I find the closest static container of the buttons (if no container use document) and any click inside the container is checked against the thing we want clicked - you can test against any valid selector.

let index = 0;
const colors = ['green', 'red', '#405cf5'];
document.getElementById("buttonContainer").addEventListener("click", function(e) {
  const tgt = e.target;
  if (tgt.matches("button.buttons")) {
    tgt.style.backgroundColor = colors[index   % colors.length];
  }
})
<div id="buttonContainer">
  <button type="button"  id="button1">1</button>
  <button type="button"  id="button2">2</button>
  <button type="button"  id="button3">3</button>
</div>

If there are other buttons not to be affected we can use a class

let index = 0;
const colors = ['green', 'red', '#405cf5'];
document.addEventListener("click", function(e) {
  const tgt = e.target;
  if (tgt.matches("button.buttons")) {
    tgt.style.backgroundColor = colors[index   % colors.length];
  }
})
  <button type="button"  id="button1">1</button>
  <button type="button"  id="button2">2</button>
  <button type="button"  id="button3">3</button>

<button >Dont color me</button>

  • Related