dangerChihuahua007
dangerChihuahua007

Reputation: 20895

How do I access elements via the DOM retrieved from $.ajax()?

I loaded some HTML from another page via $.ajax:

<script type="text/javascript">
    $(function() {
        $.ajax({
            url: '/getInfo',
            context: $('#contentBox'),
            success: function(data) {
                $(this).html(data);
            }
        });
    });

    $(function() {
        $('#clickableElement').click(function() {
            alert("I work!");
        });
    });
 </script>

 <div id="contentBox"></div>

The code loads this HTML into the div with ID contentBox:

<p id="clickableElement">I'm clickable.</p>

However, when I click on the paragraph loaded, no alert box pops up. I don't think I am accessing the DOM correctly when it comes to elements loaded via AJAX. How can I fix this?

Upvotes: 1

Views: 4305

Answers (2)

gdoron
gdoron

Reputation: 150253

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+

on version:

$('#contentBox').on('click', '#clickableElement', function () {
    alert( 'I work!' );
});

on docs:

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

Upvotes: 5

AbstractProblemFactory
AbstractProblemFactory

Reputation: 9811

When browser run your script, there is no node with id = clickableElement, you must mark that the element could be created later also.

To access dynamic DOM nodes, you should use on() function from jQuery.

Upvotes: 0

Related Questions