Setting Link Href From Child Image Src Using Jquery
I am using .wrap() to create a link around each image within a certain
, and I need to set that link's href to be equal to that image's src value. I figured out how to d
Solution 1:
Try this and read through it. There are a few things that are worth knowing in these few lines. It is much like CephalidOne's solution but might be a bit easier to understand.
$('div.divclass img').each(function(){
var $this = $(this);
$this.wrap('<a href="' + $this.attr('src') + '"></a>');
});
See it work: http://jsfiddle.net/AAdWH/
Solution 2:
$('.divclass img').wrap(function() {
return'<a class="linkclass" href="' + $(this).attr('src') + '" />';
});
Solution 3:
instead of :
$(this).find('img')
use:
$(this).children('img')
and your wrap is formatted incorrectly.
so in the end your code would be:
$('.divclass img').wrap("<a class='linkclass' />");
$('a.linkclass').attr("href", $(this).children('img').attr('src'));
or change your code completely:
example (the fiddle):
$('.divclass').children('img')
.each(function(){
var $this = $(this)
$this.wrap("<a class='linkclass'/>")
$this.parent('.linkclass').attr("href", $this.attr('src'));
});
Post a Comment for "Setting Link Href From Child Image Src Using Jquery"