Search code examples
javascriptjqueryimageword-wrap

How to wrap var img = new image with tag?


Trying to preload images in a loop and it works fine but how to wrap each image with another tag. Doing this code won't work and I can't see a problem so far.

...
var img = new Image();
$(img).load(function(){
$(this).hide();         
$('.container').append('<a href="/">'+this+'</a>');                                                     $(this).fadeIn();                                       
});
...

Solution

  • You can't do '<a href="/">'+this+'</a>' when this is a DOMElement.

    A good solution can be:

    // Inside the callback
    $('<a href="/"></a>').append(this).appendTo('.container');
    

    Remember that if you use .wrap it will return the original element, not the wrapper!