Jeremy Nelson
Jeremy Nelson

Reputation: 286

Wrap all images in html string with jquery

looked around and couldn't find anything that helps

I need a function that replaces all images in a string with wrapped images with matching href then returns a string.

content = "<html>";
var $content = $(content);
$('img', $content).each(function () {
        $(this).html().replace($(this).html(),'<a href="' + $(this).attr('src') + '" target="_blank" class="thumbnailLink"><img src="' + $(this).attr('src') + '" style="' + $(this).attr('style') +'"></a>')                    
    }); 
    return  $content.html();

Upvotes: 2

Views: 526

Answers (2)

sinisake
sinisake

Reputation: 11328

Here is possible solution, hope it will work for you.

content = '<div class="img"><img src="fjords.jpg" alt="Fjords" width="300" height="200"><div class="desc">Add a description of the image here</div></div><div class="img"><img src="forest.jpg" alt="Forest" width="300" height="200"><div class="desc">Add a description of the image here</div></div><div class="img"><img src="lights.jpg" alt="Northern Lights" width="300" height="200"><div class="desc">Add a description of the image here</div></div><div class="img"><img src="mountains.jpg" alt="Mountains" width="300" height="200"><div class="desc">Add a description of the image here</div></div>';
html = $( content );


$('img',html).each(function () {
$(this).wrap('<a href="' + $(this).attr('src') + '" target="_blank" class="thumbnailLink"> </a>');    

    }); 
final=[];
$.each(html, function(index, value) {
    final.push($(value).html());
}); 

console.log(final.join(''));

So, simple wrap images inside $content, and then iterate through object, make jQuery object from value, to get html(), and output final string.

DEMO>https://jsfiddle.net/vaxL8d9p/1/

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55750

You could just set the html instead of reading and replacing it.

$('img', $content).each(function () {
    var src = $(this).attr('src');
    var style = $(this).attr('style');
    $(this).html('<a href="' + src + '" target="_blank" class="thumbnailLink"><img src="' + src + '" style="' + style +'"></a>'); 
});

Upvotes: 0

Related Questions