Delegation for dynamic elements using JQuery on()

Published:
Updated:
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.
 
JQuery on() usage is as follows: 
$(selector).on(event, childSelector, function)

Open in new window


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:
 
<div id="parent">
                         <div class="child"> child 1</div>
                      </div>

Open in new window


Your parent selector will use the ID "parent"
"#parent"

Open in new window

As stated above, you can alternatively select the body tag for your parent.

"body"

Open in new window

Your child selector for the dynamic elements will use the class "child".

".child"

Open in new window


To create your JQuery call, pass the parent selector as the “selector” argument and the child selector as the “childSelector” argument.
 
$("#parent").on("click", ".child", function (e) { //do something });

Open in new window


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:
 
<div id="parent">
                         <div class="child">child 1</div>
                         <div class="child">child 2 added dynamically</div>
                         <div class="child">child 3 added dynamically</div>
                      </div>

Open in new window


In this case, all three of the child elements will perform the function on click. 
 
That is how to use JQuery on() to perform delegation on dynamically added DOM elements.  This will help you make a cleaner page using simpler code.
0
4,233 Views

Comments (0)

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.