Linked Questions

Popular Questions

Apply jQuery to dynamically inserted divs

Asked by At

I am writing a userscript using jQuery. I am trying to change the content of the divs with the class foo so it contains bar. With a static list of elements, I can do it using $(document).ready():

// The userscript
$(document).ready(function() {
  $(".foo").text("bar");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="content">
  <div class="foo">foo</div>
  <div class="foo">foo</div>
</div>

However, I can't figure out how to replace the text of divs that get inserted dynamically:

// The userscript
$(document).ready(function() {
  $(".foo").text("bar");
});

// A function to dynamically add another div:
$("#add").click(function() {
  $("<div></div>").text("foo").addClass("foo").appendTo("#content");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="content">
  <div class="foo">Div 1</div>
  <div class="foo">Div 2</div>
</div>
<button id="add" type="button">Add</button> // Click to 

Using $(document).ready() only works on the statically inserted divs, as those are the only ones there when the document is loaded.

How can I make the divs that are dynamically added to #content get their content changed to bar?

Related Questions