title: Unable to target JS generated button within an array with a function, getting "Cannot read property 'setAttribute' of null" error
body: <p>I'm simply trying to cause a specific button background to change when I click it.
  I generated 100 buttons (in the hopes of making a simple game, later on) as an array through a for loop, while assigning an id and a distinct function call (based on the incrementing 'i' value of the loop), and am unable to actually cause the background to change upon clicking, getting the followed error instead
  &quot;Uncaught TypeError: Cannot read property 'setAttribute' of null
  at showOptions (brain.js:31)
  at HTMLButtonElement.onclick (index.html:15)&quot;</p>
  <p>My code goes as follows</p>
  <pre class="lang-js prettyprint-override"><code>var btn = [];
  function generateBoard() {
    for (i = 0; i &lt; 100; i++) {
      var modulo = i % 10;
      var up, forLeft;
      btn[i] = document.createElement(&quot;BUTTON&quot;);
      var element = document.getElementById(&quot;body&quot;);
      //btn[i].innerText = &quot;CLICK ME&quot;;
      element.appendChild(btn[i]);
      btn[i].style.backgroundColor = &quot;white&quot;;
      btn[i].id = i;
      btn[i].style.width = &quot;50px&quot;;
      btn[i].style.height = &quot;40px&quot;;
      btn[i].style.position = &quot;absolute&quot;;
      btn[i].style.top = modulo * 100;
      btn[i].style.left = Math.floor(i / 10) * 100;
      btn[i].x = (i + 10) % 10;
      btn[i].y = Math.floor(i / 10);
      document
        .getElementById(btn[i].id)
        .setAttribute(&quot;onclick&quot;, &quot;showOptions(i)&quot;);
      btn[i].innerText = btn[i].id;
  
      console.log(
        btn[i].id +
          &quot; &quot; +
          btn[i].style.left +
          &quot; &quot; +
          btn[i].style.top +
          &quot; &quot; +
          btn[i].x +
          &quot; &quot; +
          btn[i].y
      );
    }
  }
  generateBoard();
  function showOptions(i) {
    document.getElementById(i).setAttribute(&quot;style&quot;, &quot;background-color: red;&quot;); //this is line 31
  }
  </code></pre>
  <p>in console.log I actually get the correct digit as btn[i].id, oddly enough.</p>
  <p>the (index.html:15) line of the error is simply</p>
  <p><code>&lt;/html&gt;</code></p>