views:

42

answers:

3

If i have "img" element id = "myimg".
Is posible to add link to "img" without edit html page using jQuery

<img id="myimg" src="image.png">

I like to make "myimg" have link like this.

<a href="test.html"><img id="myimg" src="image.png"></a>

Thank you for reploy.

+1  A: 

You can use wrap():

$("#myimg").wrap("<a href='test.html'></a>');

or

$("#myimg").wrap($("<a>").attr("href", "test.html"));

or:

var a = $("<a>").attr("href", "test.html");
$("#myimg").wrap(a);
cletus
+2  A: 
$(document).ready(function() {
        var src = "linkhere.html";
        var a = $("<a/>").attr("href", src);
        $("#myimg").wrap(a);
});
Tr1stan
wrap is doing what I tried to achieve using javascript. Definitely +1
Kangkan
+1  A: 

I am not into jQuery. Using Javascript, you can do something like:

var parentEl = document.getElementById("myimg").parent;
var imgEl = parentEl.innerHtml;
parentEl.innerHtml = '<a href="test.html">' + imgEl + '</a>';
Kangkan