Osman Osman - 3 months ago 7x
Javascript Question

How to wrap a link around a div jQuery?

The code below should a user to click on a button of which he is prompted for a URL. Once a URL is entered, a new

element is created with a link to the inputted URL wrapped around it as an

The code works however the link tag isn't created - how do I go about doing this?

The new link should be wrapped around that specific div only.


<script type="text/javascript">
$(function() {
$(".twitter_new").click(function() {
link = prompt("Paste a url");
if (link == null) {
else {
div = document.createElement('i');
$(div).addClass("fa").addClass("fa-twitter").wrapAll('<a href="' + link + '"></a>');


Your wrapAll() expression doesn't modify what the variable div is. It returns a new object.

You are still appending the original i element only

I would suggest you create 2 elements or do this all as html string

// create `<i>`
var $i = $('<i>',{class: 'fa fa-twitter'});
// create <a> and append <i>
var $a = $('<a>', {href:link}).append($i);
// append complete <a> to dom