Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create link on image using Javascript

<div id="mydiv">
<img src="myimage.jpg" />
</div>
<script language="javascript">
var a=document.createElement('a');
a.href='http://mylink.com';
document.getElementById('mydiv').appendChild(a);
</script>

The script doesn't work to create link on image

<div id="mydiv">
    <a href="http://mylink.com"><img src="myimage.jpg" /></a>
</div>
like image 909
Kurniawan Avatar asked Dec 07 '22 10:12

Kurniawan


1 Answers

You are putting the link after the image.

You need to move the image so it is inside the link.

var image = document.getElementById('mydiv').getElementsByTagName('img')[0];
a.appendChild(image);
like image 147
Quentin Avatar answered Dec 25 '22 11:12

Quentin