user1751287
user1751287

Reputation: 501

dynamically added content via ajax call can not be targeted with jquery

I am passing dynamically generated html via ajax call, see simple example below

var loadContent = function(){

    $.ajax({
         url: '/url',
         method: 'GET'
    }).success(function (html) { 

         $('.content-wrapper').replaceWith(html);

    }) 

    //this is how simple returned html looks like
    //<div class="content-wrapper"><ul"><li>test</li></ul></div>

};

now if I try to target li to add class nothing happens

var testAjaxGeneratedHtml = function() {
    loadContent();
    $('.content-wrapper ul li').addClass('test');
}

Upvotes: 1

Views: 42

Answers (2)

Doug McLean
Doug McLean

Reputation: 1309

Nitin's answer is correct but I felt I could add a little more explanation...

Most Javascript functions are synchronous - each step has to finish before the next one can begin. Ajax is different, as it consists of a request and a response. It sends the request and establishes a listener to await the response and process it when it comes. Once this listener has been created, your code can continue to run while the response is still pending.

So in your case, you're sending a request and then manipulating the DOM before the response has come back. Presumably a fraction of a second later, the response arrives, your "success" function processes it, and this overwrites what you had momentarily achieved with $('.content-wrapper ul li').addClass('test');

Probably the best solution is to do as Nitin suggested and put that line inside your success handler, but if you must do it inside the testAjaxGeneratedHtml for some reason you can define it as a function:

note: untested code

var loadContent = function(onSuccess){

    $.ajax({
         url: '/url',
         method: 'GET'
    }).success(function (html) { 

         $('.content-wrapper').replaceWith(html);
         onSuccess();

    }) 

    //this is how simple returned html looks like
    //<div class="content-wrapper"><ul"><li>test</li></ul></div>

};

var testAjaxGeneratedHtml = function() {
    loadContent(function() { $('.content-wrapper ul li').addClass('test'); });
}

Upvotes: 3

NITIN PATEL
NITIN PATEL

Reputation: 460

Ajax is asynchronous request it will not wait for the response so add class inside success function after ajax has performed its task completely

var loadContent = function(){

    $.ajax({
         url: '/url',
         method: 'GET'
    }).success(function (html) { 

         $('.content-wrapper').replaceWith(html);
         $('.content-wrapper ul li').addClass('test');


    }) 

    //this is how simple returned html looks like
    //<div class="content-wrapper"><ul"><li>test</li></ul></div>

};

Upvotes: 4

Related Questions