Question

I am inserting the HTML response from an AJAX call into my page, but then when I try to access those elements after they have been created, it fails..

This is how i retrieve and insert the HTML:

$.ajax({url: 'output.aspx',
   data: 'id=5', 
   type: 'get', 
   datatype: 'html',
   success: function(outData) {$('#my_container').html(outData);} 
})

The outcome HTML, which is inserted into the <div> (id = my_container) looks like:

<div id="my_container">
   <ul>
      <li id="578" class="notselected">milk</li>
      <li id="579" class="notselected">ice cream</li>
      <li id="580" class="selected">chewing gum</li>
   </ul>
</div>

...and afterwards, when I try to access any of the <li> elements using queries like: $('#my_container li:first') or $('#my_container ul:first-child') or similar, nothing gets selected.

I am using the Listen plugin to detect any click events on the <li>elements and it works... But i couldn't figure out how to detect if the div is populated with the output HTML and accordingly change one of the <li>'s class for example...

$(document).ready does not work either...

Imagine I need to change the css style of the second <li>.. what is the solution to this?

Was it helpful?

Solution

How are you checking to see whether your AJAX call has completed? Because it's asynchronous, the elements will not, of course, be available to the code which executes immediately after your $.ajax(…) call.

Try manipulating those elements from within the success function or in other code which is called from there — at that point, you will know that the content is available.

OTHER TIPS

Are you sure your actual request is successful? If nothing is selected, the most probably reason is that nothing was actually inserted into #my_container in the first place.

First, try the following code (in place of the original AJAX call you showed):

var html = $.ajax({url: 'output.aspx',
   data: 'id=5', 
   type: 'get', 
   datatype: 'html',
   async: false
}).responseText;
$('#my_container').html(html);

If that works, your li:first selector is just being called before the AJAX request finishes. If that doesn't work, try the following code:

$.ajax({url: 'output.aspx',
   data: 'id=5', 
   type: 'get', 
   datatype: 'html',
   success: function(outData) { $('#my_container').html(outData); }, 
   error: function(errorMsg) { alert('Error occured: ' + errorMsg); }
});

That will cause an error message to pop up if the request fails. If an error message pops up with an error message, the request is not returning.

it's looks like you are trying to access to those elements before their was created because your current ajax call is asynchronous, try to put the option: "async=false" to your ajax and it should be work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top