Can't access dynamically generated div with Jquery

Posted by Bug Magnet on Stack Overflow See other posts from Stack Overflow or by Bug Magnet
Published on 2010-12-30T06:48:23Z Indexed on 2010/12/30 6:54 UTC
Read the original article Hit count: 224

Filed under:

Still trying to get my head around JQuery and dynamically generated content.

I have the following code that is dynamically generated with JQuery whenever a user clicks on an 'Add' button:

<div id="practices_div" style="border-top: 1px dotted gray">
    <br/>
    <a href="#" class="remove_link" rel="practices_div">Remove</a>
    ....content goes here
</div>

The JQuery code that dynamically loads the above content is as follows:

$.ajax({
  url: '/addAjax.html',
  success: function(response) {
    $('#container').append(response);
  }
});

What I'm trying to do is when a user clicks on the Remove link, JQuery should hide and delete the dynamically generated content from the page. The code that does this is as follows:

$('.remove_link').live('click', function() {
      if (confirm("Remove this item?"))
      {
         $('#practices_div').fadeOut('medium', function() {
           $(this).remove();
         });
      }

    return false;
});

So, when the content is dynamically loaded via Ajax, and I click on the Remove link, the Confirmation dialogue box is displayed and if I confirm, nothing happens.

For some reason, JQuery is not able find the dynamically generated #practices_div.

Any idea what I may be doing wrong?

© Stack Overflow or respective owner

Related posts about jQuery