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…

http://jsfiddle.net/fFgwb/


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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!