tags:

views:

40

answers:

4

I load content via Ajax and then I'll have element like $('.my_content_class') and I load data there like this $('.my_content_class').load(url); , but how can I match all a elements inside that new content that I loaded to .my_content_class? I tried but it didn't work at all.

$('.my_content_class a').each(function() 
{
     doSomething($(this));
});
A: 

You have to use the live() function of jQuery for this. It was added in jQuery 1.3.

Artem Russakovskii
+1  A: 

you can actually do this directly from your ajax content if need be, without having to load it into another container

$('a', content_returned_from_ajax).each( function() { 
   //dostuff 
});
Xian
I used this, but other answers were good too...
newbie
+3  A: 

$('.my_content_class a') is the way to do it. What you are probably experiencing is that you run that function before the contents was loaded. AJAX is working asynchronously so your script doesn't end until the contents is loaded before proceeding to the next line of code. You should place your code in load method callback so it's executed after AJAX requests completes his work.

var url = 'http://example.com/test.html';
var data = {var1: foo, var2: bar};
$('.my_content_class').load(url, data, function () {
     // this will be executed after the content was successfully loaded
});

From what I can read in the docs callback is called once AJAX finishes its work and I'm not sure if this is after the actual contents was loaded to the DOM tree. You need to figure this out on your own and if it's done before that you have to create some small delay in callback function to launch after DOM was updated. setTimeout may come handy for that but first I would make sure that you need that part.

RaYell
+1 for a detailed answer.
rahul
+3  A: 

You can use the callback parameter of the load function to know exactly when the loading finishes, and then you can select your elements:

$('.my_content_class').load(url, function () {
  var anchors = $('a', this); // all loaded anchor elements 
});
CMS