JQuery add <a> tag around <img>

How to add aroud tag with link to this image using jQuery?

+5
source share
2 answers

This will complete the set of images with links to them:

$('some selector for the images').each(function() {
    $(this).wrap("<a href='" + this.src + "'/>");
});

... uses .each( link ), .wrap( link ) and the DOM src() property for image elements.

Edit Or, if Pointy points out (but not clearly), just pass the function to wrap:

$('some selector for the images').wrap(function() {
  return "<a href='" + this.src + "'/>";
});

Real time example

+21
source
$('#img').each(function(){
    var $this = $(this); 
    $this.wrap('<a href="' + $this.attr('src') + '"></a>');
});
+6
source

All Articles