browntoast browntoast - 1 month ago 26
HTML Question

Detect image path in HTML image reference and create a link

How do i detect the path of a HTML image reference and add a specific hyperlink reference.

For example:

<div class="description">
<img src="https://www.example.com/image/hello.jpg">
</div>


After a script detects the image url it should build a code like this:

<div class="description">
<a class="fancybox" href="https://www.example.com/image/hello.jpg">
<img src="https://www.example.com/image/hello.jpg">
</a>
</div>


I think i need a script, but i have no experience in javascript

Answer Source

I would recommend you add a class to each img unless you plan on doing this for every img tag.

$("img").wrap(function(){
    return $("<a>").attr("href", $(this).attr("src")).addClass("fancybox");
})