April 18, 2012
Take href of an anchor in a container and apply it to image
Question by Liam
I have a list of DIV’s that all contain a piece of text, an image, and an anchor.
With Javascript/jQuery, is it possible to take the href of the anchor, and wrap the image in anchor tags with that link?
I know this is a strange requet, Ive made a fiddle…
There will be multiple divs so I cant have the same id
Answer by Starx
Here is a way
var src = $("#imgid").attr("src"); //take out the src
$("#imgid").wrap($('<a href="'+src+'" />'); //wrap around it with the anchor
Your usage, can be something like
$("img", $("#divid")).each(function() {
var src = $(this).attr("src"); //take out the src
$(this).wrap($('<a href="'+src+'" />')); //wrap around it with the anchor
});
Here is a demo with this implementation on your fiddle.