alega
alega

Reputation: 37

looping on elements loaded by .load()

I'm using .load() method to get some data on ('document').load() event, but i'm not able to loop over elements within loaded content.

here's my code:

$('document').ready(function() { 
    $('#questions').load('survey/questions');
    $('.questions').each(function() {
        alert($(this).attr('id'))
    })
});

thanks!

Upvotes: 0

Views: 114

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039538

You could loop through the contents only once the AJAX call completes (remember that AJAX is asynchronous meaning that when you call the .load() the method simply sends a request to the server but the response could come much later). That's why this function provides a callback which will be invoked once the AJAX call completes and where you could manipulate the result from the server:

$('document').ready(function() { 
      $('#questions').load('survey/questions', function() {
          // Remark: your original selector was #questions whereas here
          // you have .questions which is not the same selector
          $('.questions').each(function() {
              alert($(this).attr('id'));
          });
      });
   });
});

Upvotes: 1

Related Questions