George
George

Reputation: 2110

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.

Upvotes: 2

Views: 1032

Answers (1)

user113716
user113716

Reputation: 322452

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

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

Upvotes: 3

Related Questions