title: How to add event with Javascript to an html tag
body: <p>I've a landingpage with dynamic html tags.
  The Problem is, that i can't select directly the tag. Its a link.
  the following code is the construct:</p>
  
  <pre><code>&lt;div id="testid"&gt;&lt;div&gt;&lt;div&gt;&lt;a href="#"&gt;Button 1&lt;/a&gt;&lt;div&gt;&lt;div&gt;&lt;div&gt;
  </code></pre>
  
  <p>Every time someone clicks on the link (a-tag) I want to fire an event like the following code:</p>
  
  <pre><code>&lt;a href="#" name="button1" onclick="dataLayer.push({'event': 'button1-click'});"&gt;Button 1&lt;/a&gt;
  </code></pre>
  
  <p>the question: what is the Javascript code to add the <code>onclick="dataLayer.push({'event': 'button1-click'})</code> attribute to the a tag.</p>
  
  <p>I tried the following code:</p>
  
  <pre><code>var d = document.getElementById("testid").firstchild;
  d.setAttribute("onclick", "dataLayer.push({'event': 'button1-click'})");
  </code></pre>
  
  <p>but it seems to the code is incorrect. The <code>a</code> tag is also not the first child; there are 2 divs between :(</p>