title: Javascript pass dynamic element id to event handler
body: <p>I have JS that creates dynamic elements. I want to add onclick events to these elements and pass the calling element's ID to the event handler so that I can use JS to change the text of the element that is clicked. </p>
  
  <p>I do that by doing something like this inside a loop:</p>
  
  <pre><code> var btnID = "button-" + x; // unique id for changing element inside of test()
  
   /* desired result is &lt;button onclick="test(&lt;runtime value of btnID&gt;)"&gt;&lt;/button&gt; */
   buttonElement.onclick = function () { test(btnID)  };
  </code></pre>
  
  <p>Unfortunately, the result is that every button element passes the <code>btnID</code> of the last element in the loop  to <code>test()</code>. Can someone explain why this happens?</p>
  
  <p><a href="https://jsfiddle.net/j519rbyn/1/" rel="nofollow noreferrer">https://jsfiddle.net/j519rbyn/1/</a></p>