Adding a click or hover event to a html element using jQuery is pretty straight forward. Thats because when the DOM is created it contains events along with it. But when you create a DOM dynamically, these elements do not contain any events.

In such cases it is necessary to bind these events to the dynamically created elements using .on() function. Scroll to the end to see the code that will help you achieve that.

Normal method.

Generally with jQuery we select an element using the following code. Here you can see the target div’s ID is given inside quotes after the $ sign.

But once the #dynamic_div is created the natural (but wrong) way of selecting the DOM will be

But this will not work because jQuery cannot select the dynamically created element. jQuery requires to select through an element which has already existed right from the first render in the browser. Usually that element which stays always in the page is body tag. Hence we use that as the selector and then follow by stating the ID or class of the element we want to select. This way jQuery is able to find the dynamic element and then bind the event to it.

Solution