Pinkie
Pinkie

Reputation: 10256

jQuery No image dimensions after append

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.

Upvotes: 0

Views: 1113

Answers (1)

mu is too short
mu is too short

Reputation: 434705

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:

var $featured = $('<div id="featured"></div>');
$('#imageTable tbody tr td img').each(function(){
    $featured.append('<img src='+$(this).attr("src")+' />');
});
$featured.appendTo('#wrapper');

Demo: http://jsfiddle.net/ambiguous/PXVG2/

Doing $(x).append(...) over and over again will work provided that x is something that is already in the DOM; your <div id="featured"> isn't such a thing. If you appended it to #wrapper first and #wrapper was in the DOM, then it would work okay if you used #featured instead of the HTML:

var featured = '<div id="featured"></div>';
$(featured).appendTo('#wrapper');
$('#imageTable tbody tr td img').each(function(){
    $('#featured').append('<img src='+$(this).attr("src")+' />');
});

Demo: http://jsfiddle.net/ambiguous/vPyy6/

This latter approach is rather wasteful though, it creates a new jQuery object on each .each iteration. The first approach is much better.

Upvotes: 2

Related Questions