I need to dynamically append a set of elements to a div via jQuery and then turn around and reference them. It’s really odd that you can’t do this, since if you view the DOM in firebug, the elements are there. jQuery just doesn’t act like they exist.
HTML…
<div id="images"></div>
This gives me my elements added to the <div>…
$.getJSON("http://localhost/wordpress/test.php",
function (data) {
$.each(data, function (i, item) {
$("<img/>").attr("src", item).appendTo("#images");
});
});
Then I immediately try to select and use the images…
$("img").each(
function (i, item) {
alert(item);
});
jQuery doesn’t select any of the newly added elements. It basically acts like none of the images were added.
I would hazard a guess that when you run the second block of code the images aren’t there yet. The getJSON call is asynchronous. This means you don’t know when it will return and add the image elements to the page.
Have you tried adding your second block of code in the same function that calls the appendTo? This is a common source of confusion when people do asynchronous code.