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
2010-10-21 12:33:01
`#img` should be `img`. It doesn't make sense to select an element that will be unique and use the `each` function. :P
BrunoLM
2010-10-21 12:46:18
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
2010-10-21 12:48:46
no, Bruno is right. you're calling each on one element. it should be $('img').
EMMERICH
2010-10-21 12:49:43
+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 + "'/>";
});
T.J. Crowder
2010-10-21 12:34:31
It's also possible to just use `.wrap()` with a function as an argument; probably a wash.
Pointy
2010-10-21 12:50:02
@Pointy: *Sigh* When will I learn?! I *know* that, and yet I keep typing `each`... Thanks.
T.J. Crowder
2010-10-21 13:23:32