tags:

views:

72

answers:

2

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

+5  A: 
$('#img').each(function(){
    var $this = $(this); 
    $this.wrap('<a href="' + $this.attr('src') + '"></a>');
});
DoXicK
`#img` should be `img`. It doesn't make sense to select an element that will be unique and use the `each` function. :P
BrunoLM
actually it does, since you need to select the element. i could have done $('#img').wrap('<a href="' + $('#img').attr('src') + '"></a>); but this shows a bit more uses of jquery. valid point though ^_^
DoXicK
no, Bruno is right. you're calling each on one element. it should be $('img').
EMMERICH
+7  A: 

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

T.J. Crowder
It's also possible to just use `.wrap()` with a function as an argument; probably a wash.
Pointy
Thanx, it works!
Simon
@Pointy: *Sigh* When will I learn?! I *know* that, and yet I keep typing `each`... Thanks.
T.J. Crowder