Osman Osman - 5 months ago 12
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

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

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.

Thanks.

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

Answer

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
$(".icons").append($a);