I have the following code, which loops to get all images in a table then appends them to #featured which is then appended to #wrapper. The problem is after everything is appended to #wrapper, images have no dimensions and for that reason non of them show. It’s like having 0px width and height for images. How do i overcome this size issue.
var featured = '<div id="featured"></div>';
$('#imageTable tbody tr td img').each(function(){
$(featured).append('<img src='+$(this).attr("src")+' />');
});
$(featured).appendTo('#wrapper');
I tried to solve this problem by doing
$(featured).load(function(){
$(this).appendTo('#wrapper');
});
But that doesn’t work.
Your problem is that every time you say
$(featured), you’re creating a brand new jQuery object; then you do something to it and throw it — and what you did to it — away. The result is that you end up appending an empty<div id="featured">to#wrapper: the images don’t come out with no dimensions, they’re just not there at all.Create one jQuery object and keep using that one object:
Demo: http://jsfiddle.net/ambiguous/PXVG2/
Doing
$(x).append(...)over and over again will work provided thatxis something that is already in the DOM; your<div id="featured">isn’t such a thing. If you appended it to#wrapperfirst and#wrapperwas in the DOM, then it would work okay if you used#featuredinstead of the HTML:Demo: http://jsfiddle.net/ambiguous/vPyy6/
This latter approach is rather wasteful though, it creates a new jQuery object on each
.eachiteration. The first approach is much better.