Accessing DOM elements after ajax.load

I am pasting the HTML response from the AJAX call to my page, but then when I try to access these elements after they are created, it doesn't work.

This is how I extract and paste the HTML:

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

      

The HTML result pasted in <div>

(id = my_container

) looks like this:

<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 after that, when I try to access any item <li>

using queries like: $('#my_container li:first')

or $('#my_container ul:first-child')

or similar, nothing is selected.

I am using the Listen plugin to detect any click events on the elements <li>

and it works ... But I couldn't figure out how to detect if the div is being filled with the output HTML and change one of the classes accordingly <li>

, eg ...

$(document).ready

doesn't work either ...

Imagine I need to change the css style of the second <li>

.. What is the solution to this?

0


source to share


4 answers


How do you check if your AJAX call has completed? Since it is asynchronous, the elements will of course not be available to code that is executed immediately after your call $.ajax(…)

.



Try manipulating these elements from a function success

or other code that is called from there - at this point you will know that the content is available.

+3


source


Are you sure your actual request was successfully completed? If nothing is selected, most likely the reason is that nothing was actually inserted in #my_container.



0


source


Try the following code first (instead 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 selector is li:first

simply called before the AJAX request completes. 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); }
});

      

This will result in an error message if the request fails. If an error message appears with an error message, the request is not returned.

0


source


it looks like you are trying to access these elements before they are created because your current ajax call is async, try putting the parameter: "async = false" to your ajax and it should work.

0


source







All Articles