title: Attach event to dynamic elements in javascript
body: <p>I'm trying to insert html data dynamically to a list that is dynamically created, but when i try to attach an onclick event for the button that is dynamically created the event is not firing. Solution would be really appreciated.</p>
  <p>Javascript code:</p>
  <pre><code>document.addEventListener('DOMContentLoaded', function () {
     document.getElementById('btnSubmit').addEventListener('click', function () {
          var name = document.getElementById('txtName').value;
          var mobile = document.getElementById('txtMobile').value;
          var html = '&lt;ul&gt;';
          for (i = 0; i &lt; 5; i++) {
              html = html + '&lt;li&gt;' + name + i + '&lt;/li&gt;';
          }
          html = html + '&lt;/ul&gt;';
  
          html = html + '&lt;input type=&quot;button&quot; value=&quot;prepend&quot; id=&quot;btnPrepend&quot; /&gt;';
          document.getElementsByTagName('form')[0].insertAdjacentHTML('afterend', html);
      });
  
      document.getElementById('btnPrepend').addEventListener('click', function () {
          var html = '&lt;li&gt;Prepending data&lt;/li&gt;';
          document.getElementsByTagName('ul')[0].insertAdjacentHTML('afterbegin', html);
      });
  });
  </code></pre>
  <p>HTML Code:</p>
  <pre><code>&lt;form&gt;
      &lt;div class=&quot;control&quot;&gt;
          &lt;label&gt;Name&lt;/label&gt;
          &lt;input id=&quot;txtName&quot; name=&quot;txtName&quot; type=&quot;text&quot; /&gt;
      &lt;/div&gt;
      &lt;div class=&quot;control&quot;&gt;
          &lt;label&gt;Mobile&lt;/label&gt;
          &lt;input id=&quot;txtMobile&quot; type=&quot;text&quot; /&gt;
      &lt;/div&gt;
      &lt;div class=&quot;control&quot;&gt;
          &lt;input id=&quot;btnSubmit&quot; type=&quot;button&quot; value=&quot;submit&quot; /&gt;
      &lt;/div&gt;
  &lt;/form&gt;
  </code></pre>