jQuery HTML Element How to - Wrap image tag with anchor tag to make it clickable








Question

We would like to know how to wrap image tag with anchor tag to make it clickable.

Answer


<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head><!--   w w  w.ja v a 2 s.  c  o  m-->
<body>
  <div>
    <img src="http://www.java2s.com/style/download.png">
  </div>
  <script>
        var images =$("div img")
        $.each(images, function() {
           $(this).replaceWith('<a href="rias">'+this.outerHTML+'</a>');
        });
</script>
</body>
</html>

The code above is rendered as follows: