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?
source to share
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.
source to share
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.
source to share