Search code examples
jqueryhtmlhyperlinkhrefvar

Jquery dynamic link creation


Consider the following Jquery code:

var previewImage = $('#prev');
var newLink = $('<a/>').attr('href', name);
previewImage.append(newLink);

The HTML output is

<img src=" " id="prev"/>
<a href=" "></a>

The required output is

<a href=" "><img src=" " id="prev"/></a>

The main problem is that the link is created after the previewImage with id="prev" and I need this image to be inside the link. Any help will be greatly appreciated.


Solution

  • You want the wrap()[docs] method instead of append()[docs].

    var previewImage = $('#prev');
    var newLink = $('<a/>').attr('href', name);
    previewImage.wrap(newLink);