title: jQuery how to bind onclick event to dynamically added HTML element
body: <p>I want to bind an onclick event to an element I insert dynamically with jQuery</p>
  
  <p>But It never runs the binded function. I'd be happy if you can point out why this example is not working and how I can get it to run properly:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"        
              "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
          &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="da" lang="da"&gt;
          &lt;head&gt;
            &lt;title&gt;test of click binding&lt;/title&gt;
  
  &lt;script src="https://code.jquery.com/jquery-1.12.4.min.js"&gt;&lt;/script&gt;
            &lt;script type="text/javascript"&gt;
  
  
          jQuery(function(){
            close_link = $('&lt;a class="" href="#"&gt;Click here to see an alert&lt;/a&gt;');
            close_link.bind("click", function(){
              alert('hello from binded function call');
              //do stuff here...
            });
    
            $('.add_to_this').append(close_link);
          });
            &lt;/script&gt;
          &lt;/head&gt;
          &lt;body&gt;
            &lt;h1 &gt;Test of click binding&lt;/h1&gt;
            &lt;p&gt;problem: to bind a click event to an element I append via JQuery.&lt;/p&gt;
  
            &lt;div class="add_to_this"&gt;
              &lt;p&gt;The link is created, then added here below:&lt;/p&gt;
            &lt;/div&gt;
  
            &lt;div class="add_to_this"&gt;
              &lt;p&gt;Another is added here below:&lt;/p&gt;
            &lt;/div&gt;
  
  
          &lt;/body&gt;
          &lt;/html&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p><strong>EDIT: I edited the example to contain two elements the method is inserted to.</strong> In that case, the <code>alert()</code> call is never executed. (thanks to @Daff for pointing that out in a comment)</p>