title: How to set onClick with JavaScript?
body: <p>I am trying to set the onclick event using javascript.  The following code works:</p>
  
  <pre><code>var link = document.createElement('a');
  link.setAttribute('href', "#");
  link.setAttribute('onclick', "alert('click')");
  </code></pre>
  
  <p>I then use appendChild to add link to the rest of the document.</p>
  
  <p>But I obviously would like a more complicated callback than alert, so I tried this:</p>
  
  <pre><code>link.onclick = function() {alert('clicked');};
  </code></pre>
  
  <p>and this:</p>
  
  <pre><code>link.onclick = (function() {alert('clicked');});
  </code></pre>
  
  <p>But that does nothing.  When I click the link, nothing happens.  I have testing using chrome and browsing the DOM object shows me for that element that the onclick attribute is NULL.</p>
  
  <p>Why am I not able to pass a function into onclick?</p>
  
  <p>EDIT:</p>
  
  <p>I tried using addEventListener as suggested below with the same results.  The DOM for the link shows onclick as null.</p>
  
  <p>My problem may be that the DOM for this element might not have been fully built yet.  At this point the page has been loaded and the user clicks a button.  The button executes javascript that builds up a new div that it appends to the page by calling document.body.appendChild.  This link is a member of the new div.  If this is my problem, how do I work around it?</p>