2012年4月25日 星期三

[soft] manipulate elements dynamically added by AJAX calls in jQuery


Recently, I have been looking for a way to manipulate elements dynamically added to the page by AJAX calls. In the best case that the corresponding AJAX event is defined by ourselves, we can simply add a callback function for execution after the AJAX call completion.

But how about the other cases?

jQuery .on() comes to the rescue for most of the cases as you can attach a handler to an existing element then wait for the events of those newly added objects to bubble up to your element. However, not every event bubbles. For instance, 'load' events are filed as simple ones that do not bubble. After doing some Google search, here is what I have got for the solution:

$(selector).on("DOMNodeInserted", function(e){
    var targetElements = $(e.target).find(selector);
    // do something
});
Generally, the idea is that we can attach a handler for the DOMNodeInserted event, then use find() to capture our target elements from the AJAX call.

Note: This does not works for I.E. with version number <= 8.