jQuery function not binding to newly added dom elements

Updated (14 Nov 2013): $.live() is deprecated. I had written another blog on the new $.on() which will do the same. http://blog.kongnir.com/2013/11/14/jquery-using-on-to-call-newly-added-elements/

I was trying to use jQuery’s .append() function to insert some HTML code into a div.

This was the HTML (Example):

<div class="conditions-basic">
	<span class="function">
		<select name="someName"
                    id="someID" class="ddlSelect">
		<option selected="selected" value="1">1</option>
		<option value="2">2</option>
		<option value="3">3</option>
	// More elements here
<div class="conditions-more"></div>

The div class “conditions-basic” contains a select input. So when a user clicks on an ADD button somewhere, I want to duplicate the same select input in div class “condition-more” by doing this:

$('#btnAnd').click( function () {
	var appendHtml = $('div.conditions-basic').html().trim();

The select input will make some changes to its own newly appended elements. However, the .change() function doesn’t work for newly added elements.
Upon some research, I had read that instead of using .change(), we should use .live() instead.

Reason: live is a late-binding dynamic handler that can attach to elements added to the DOM after the handler is declared. See documentation for more info.

Instead of using .change() event directly like this:

$('.ddlSelect').change(function () {
    alert("this is not working");

Use .live() like this:

$('.ddlSelect').live("change", function () {
    alert("this is working");

Reference: http://stackoverflow.com/questions/6537323/jquery-function-not-binding-to-newly-added-dom-elements


  • Chaim Leichman

    November 14, 2013

    FYI – $.live has been deprecated. jQuery now favors using $.on() to achieve this. Check out the API doc for details on how to migrate…

    • Andrews Ang

      November 14, 2013

      Hey thanks, you’re right. I’m aware of that. This blog was written way before that change.

    • Andrews Ang

      November 14, 2013

      I had written a new blog on $.on(). Hope this helps other fellow programmers. Cheers

Comments are closed.