Decrypter
Decrypter

Reputation: 3000

Listening for the addition of certain elements to the DOM by AJAX

I have a web application which uses a lot of AJAX to display pages. In my javascript I have a feature which gets all the elements that have a certain class (testClass). It does a bunch of stuff with these classes but that's not necessary for my problem.

At the moment my function runs when the DOM is ready and it works great. However, I need my function to run when AJAX returns a new page to the browser as it could contain elements with testClass.

Is there a way I can listen if a certain DOM element is added? I basically need a way to recognise a DOM change, when this change has happen run my function. Or is there a way I can listen for the addition of elements with class testClass?

If it help here is a snippet of my code:

execute = function () {
    var found = false;
    $('.testClass').each(function () {
        //bunch of code
    });
}
$(document).ready(function () {
    execute();
});

Upvotes: 0

Views: 69

Answers (1)

Dipak
Dipak

Reputation: 12190

Try with ajax success method

$.ajax({
  url: 'ajax/test.html',
  success: function(data) {
    $('.result').html(data);
    alert('Load was performed.');
  }
});

Upvotes: 1

Related Questions