Lee
Lee

Reputation: 27

How to Use Id Name in a Loop in JS?

I'm trying to make a game with Javascript.

There's a part where 42 spans should randomly have color distributed.

I am guessing my code is not working because of this part below:

document.getElementById('s\'i\'').style.backgroundColor = color[c];

I hope there's a way to use a loop with id names

var color = ["#FCB711", "#F37021", "#CC004C", "#6460AA", "#0080D0", "#0DB14B"];
var i;
for (i = 1; i <= 42; i++) {
  document.getElementById('demo').innerHTML = getRndInteger(0, 6);
  document.getElementById('s\'i\'').style.backgroundColor = color[c];
}

function getRndInteger(min, max) {
  var c = Math.floor(Math.random() * (max - min)) + min;
}
<span id="s1">s1</span><span id="s2">s2</span>
<span id="s3">s3</span><span id="s4">s4</span> ...

<span id="s40">s40</span> <span id="s41">s41</span><span id="s42">s42</span>

Upvotes: 1

Views: 367

Answers (2)

acarlstein
acarlstein

Reputation: 1838

Let me know if you have questions about the code below.

First, you could give all your elements the same class. In this way, you can obtain references to each of them. Plus, it gives you the advantage of adding more elements if you want by just adding a span. So, if you go from 42 to 43, you don't need to modify the conditional of your loop.

function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

// Wait for all DOMs to be loaded prior to run the code
document.addEventListener("DOMContentLoaded", function(event) { 
  document.getElementById('demo').innerHTML = getRndInteger(0,6);      
  var colors = ["#FCB711", "#F37021", "#CC004C", "#6460AA", "#0080D0", "#0DB14B"]; 
  var elems = document.getElementsByClassName("elems");
  for(var i = 0; i < elems.length; ++i){
    var index = getRndInteger(0,6);
    var elem = elems.item(i);
    elem.style.backgroundColor = colors[index];
  }
});
<span class="elems" id="s1">s1</span>
<span class="elems" id="s2">s2</span>
<span class="elems" id="s3">s3</span>
<span class="elems" id="s4">s4</span>
<span class="elems" id="s5">s5</span>
<span class="elems" id="s6">s6</span>
<span class="elems" id="s7">s7</span>
<span class="elems" id="s8">s8</span>
<span class="elems" id="s9">s9</span>
<span class="elems" id="s10">s10</span>
<div id="demo"></div>

Upvotes: 0

labu4bd
labu4bd

Reputation: 701

I assume i have 4 <span> against your 42 <span>s.

  var color = ["#FCB711", "#F37021", "#CC004C", "#6460AA", "#0080D0", "#0DB14B"];
  var i;
  for (i = 1; i <= 4; i++) { 
    document.getElementById('demo').innerHTML = getRndInteger(0,6);
    document.getElementById('s'+i).style.backgroundColor = color[getRndInteger(0,6)];
  }

  function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
  }
<span id="s1">s1</span>
<span id="s2">s2</span>
<span id="s3">s3</span>
<span id="s4">s4</span>

<span id="demo">Demo</span>

Upvotes: 3

Related Questions