Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery add tag <a> around <img>

Tags:

jquery

How can I add tag aroud with link to that image with JQuery?

like image 237
Simon Avatar asked Oct 21 '10 12:10

Simon


2 Answers

This will wrap a 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 native DOM src (link) property for image elements.

Edit Or as Pointy points out (but not pointedly), just pass a function into wrap:

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

Live example

like image 148
T.J. Crowder Avatar answered Oct 01 '22 02:10

T.J. Crowder


$('#img').each(function(){
    var $this = $(this); 
    $this.wrap('<a href="' + $this.attr('src') + '"></a>');
});
like image 41
DoXicK Avatar answered Oct 01 '22 01:10

DoXicK