I have a div which in jquery’s document ready I append – using $("#div id").append('html text') syntax – with 10 or so more div child elements.
once this is done I try to check the content of the child divs via alert($(".classname")); and it comes back with:
function(a){if(c.isFunction(a))return this.each(function(b){var d=c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)}
I would have expected it to alert with the html contents of the child divs and not javascript?
full script:
<script type="text/javascript">
$(document).ready(function(){
// twitter api's base url
var url="http://search.twitter.com/search.json?callback=?&result_type=recent&q=";
// we'll store the search term here
var query = "blah";
// get the json file
$.getJSON(url+query,function(json){
// this is where we can loop through the results in the json object
$.each(json.results,function(i,tweet){
// this is where we do what we want with each tweet
$("#results").append('<div class="tweetBox"><span class="unseen">'+tweet.created_at+'</span><div class="tweetImg"><img src="'+tweet.profile_image_url+'" width="48" height="48" /><a class="overbox" href="http://twitter.com/'+tweet.from_user+'/status/'+tweet.id+'"></a></div>'+tweet.text+' ...said '+((new Date().getTime()/1000/60)-(new Date(tweet.created_at))/1000/60).toFixed(0)+' minutes ago</div>');
});
});
$("#results").height(function(){return $(window).height()-204;});
alert($(".unseen").html());
});
</script>
<div id="results"></div>
update:
definitely some kind of jquery/javascript race condition going on here, if I replace the alert with setTimeout(function(){alert($(".unseen").html());},1000); it returns the text expected. If I change the timeout pause to 1 millisecond it returns null once again.
Not sure of a ‘real’ workaround for this other than sticking in the delay?
Ajax calls (like
$.getJSON) are done asynchronously.This means that when the jQuery selection is done(at the bottom of the script) the response might not be received yet (still on the way).
You have to move all the code that depends on elements created from the response in the callback function (right after the
$.each(...);)Ex:
Also note that the html() function returns the html contents of only the first element in the set.
EDIT: your timeout trick works because it gives the ajax call the time it needs to complete and trigger the callback function that ads the objects to the DOM.
See working example here.