Add Hyperlink to images using jQuery
jQuery provides a method named "wrap()", which can be used to insert any HTML structure in set of matched elements. In simple words, if you want put wrapper around your div element then you can use wrap() method. For example, you have a div with ID "Child".
<div id="Child"></div>
And want to wrap this div with any parent then you can use "wrap()" method to insert HTML.
$('#Child').wrap('<div id="Parent"></div>');
Output:
<div id="parent"> <div id="child"></div> </div>
Same way, we will use the wrap() method to insert hyperlink to image tag so that the image becomes clickable. See below.
$(document).ready(function() { $('img').each(function () { var currentImage = $(this); currentImage.wrap("<a href='" + currentImage.attr("src") + "' </a>"); }); });
In the above code, the wrap function wraps the anchor tag around each image with using the image source as Hyperlink for a tag. For demo, I have added "target=_blank" attribute so that it opens in a new tab/window.
See result below.
If you want to add same Hyperlink to every image then you can use below code. Just replace the URL (My blog URL) with your required URL.
$(document).ready(function() { $('img').wrap("<a href='http://jquerybyexample.blogspot.com' </a>"); });
Feel free to contact me for any help related to jQuery, I will gladly help you.