Add link to image dynamically

26,046

Solution 1

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);

Solution 2

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

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

Solution 3

$(document).ready(function() {
        var src = "linkhere.html";
        var a = $("<a/>").attr("href", src);
        $("#myimg").wrap(a);
});
Share:
26,046
wearetherock
Author by

wearetherock

Updated on June 04, 2020

Comments

  • wearetherock
    wearetherock almost 4 years

    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>
    
  • Kangkan
    Kangkan about 14 years
    wrap is doing what I tried to achieve using javascript. Definitely +1
  • Sam
    Sam over 12 years
    Also how can we remove link i.e. <a> tag if already exist for an image.
  • Kangkan
    Kangkan over 12 years
    @SamyagShah: You can possibly use a RegEx evaluator and replace the anchors with '' to remove the anchor. That should be quite simple.
  • Sam
    Sam over 12 years
    thanks for answer. But is there any other way i.e. by using javascript functions like removeChild,etc.
  • Kangkan
    Kangkan over 12 years
    That should be posted as a separate question. That might help fellow users, rather than getting it here.