title: Dynamically create onclick event anchor element - Javascript
body: <p>How do I dynamically create a onclick function in a hyperlink in JavaScript?</p>
  <p>This is a code snippet - a while loop that creates several hyperlinks within the same page. I tried to just add the onclick event to the a-element, that is:</p>
  <pre><code>a.onclick=myfunction()
  </code></pre>
  <p>However, when the page is loaded with a list of these links, the function is automatically called for every link.</p>
  <p>This is how my code looks like. I guess I should use an <strong>id</strong> for every link?</p>
  <pre><code>  var a = document.createElement('a');
    var linkText = document.createTextNode(child.innerHTML);
    a.appendChild(linkText);
    a.title = child.innerHTML;
    a.href = &quot;#stockContent&quot; + i;
    a.id = &quot;link_id&quot; + i;
  
    ...
  </code></pre>
  <p>&quot;i&quot; is the iterator variable.</p>