title: Apply jQuery to dynamically inserted divs
body: <p>I am writing a userscript using jQuery. I am trying to change the content of the divs with the class <code>foo</code> so it contains <code>bar</code>. With a static list of elements, I can do it using <code>$(document).ready()</code>:</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-js lang-js prettyprint-override"><code>// The userscript
  $(document).ready(function() {
    $(".foo").text("bar");
  });</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;
  
  &lt;div id="content"&gt;
    &lt;div class="foo"&gt;foo&lt;/div&gt;
    &lt;div class="foo"&gt;foo&lt;/div&gt;
  &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>However, I can't figure out how to replace the text of divs that get inserted dynamically:</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-js lang-js prettyprint-override"><code>// The userscript
  $(document).ready(function() {
    $(".foo").text("bar");
  });
  
  // A function to dynamically add another div:
  $("#add").click(function() {
    $("&lt;div&gt;&lt;/div&gt;").text("foo").addClass("foo").appendTo("#content");
  });</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt;
  
  &lt;div id="content"&gt;
    &lt;div class="foo"&gt;Div 1&lt;/div&gt;
    &lt;div class="foo"&gt;Div 2&lt;/div&gt;
  &lt;/div&gt;
  &lt;button id="add" type="button"&gt;Add&lt;/button&gt; // Click to </code></pre>
  </div>
  </div>
  </p>
  
  <p>Using <code>$(document).ready()</code> only works on the <em>statically</em> inserted divs, as those are the only ones there when the document is loaded.</p>
  
  <p>How can I make the divs that are <em>dynamically</em> added to <code>#content</code> get their content changed to <code>bar</code>?</p>