How To: jQuery - Bind Events To Dynamically Created Elements

Event handlers can only be bound to currently selected elements. In other words, they must exist on the page at the time your code makes the call to the jQuery.fn.on method. However, jQuery provides a selector string to filter the descendants of the selected elements that trigger the event. This is evaluated at the time that the event is triggered.

Step by Step

HTML for the Parent Element

<div id="parent"></div>

JavaScript to Create the Event Handler

$("#parent").on("click", "div.child", function (event) {
  console.log(event.target);
});

Add the Child Elements

for (var idx = 0; idx < 5; idx++) {
  $("#parent").append("<div class='child' style='width:100px;height:100px;background-color:blue;'></div>");
});

Example

The example has a div element with an id of container. A click event handler is added to the container element with a "selector" as the second parameter to filter the descendants of the container element. Child elements are added to the container element

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License