There are a couple ways to attach a JavaScript function to dynamically created elements. You can make a new script for each element as it’s created or you can use delegation.
Delegation allows a single script that is added at page creation to match elements that will be added later. This will decrease the number of script elements on your page and eliminate the need for unique classes or IDs on each dynamic element. With the JQuery delegate() method being deprecated, the way to do this is using the JQuery on() method.
To use delegation, you must be able to create a selector for a parent element to your dynamically added elements. If you have no better choice, selecting the body tag will work. You will also need to create your dynamic elements in such a way that they can all match a common selector. Your DOM structure will look something like this:
This will match any element with the “child” class that is contained within the element with the “parent” id, including any that are added after page creation. After dynamically adding a couple child elements to the parent, your DOM structure may look like this:
Comments (0)