MultiDev
MultiDev

Reputation: 10649

Using jQuery to wrap elements in a hyperlink

I have:

<div id="facebook">
    <span class="fa-stack fa-lg"><i class="fa fa-circle-thin fa-stack-2x"></i><i class="fa fa-facebook fa-stack-1x"></i></span><br /><span id="soc_fb"></span>
</div>

And on a certain action, I want to wrap the whole thing in a hyperlink like:

<div id="facebook">
    <a href="http://www.facebook.com"><span class="fa-stack fa-lg"><i class="fa fa-circle-thin fa-stack-2x"></i><i class="fa fa-facebook fa-stack-1x"></i></span><br /><span id="soc_fb"></span></a>
</div>

So, what I tried was:

$("#facebook").prepend('<a href="#" title="Facebook" class="facebook_c">').append('</a>');

But this does not seem to do anything. Any ideas?

Upvotes: 2

Views: 81

Answers (3)

Rob Schmuecker
Rob Schmuecker

Reputation: 8954

You can also use wrap http://api.jquery.com/wrap/

$("#facebook").wrap('<a href="#" title="Facebook" class="facebook_c">');

which wraps the entire #facevook div

or

You can also use wrapAll http://api.jquery.com/wrapall/

$("#facebook").children().wrapAll('<a href="#" title="Facebook" class="facebook_c">');

Which wraps just the contents of #facebook div

Demo: http://jsfiddle.net/robschmuecker/2K6bL/

Upvotes: 1

Paul Roub
Paul Roub

Reputation: 36438

prepend() and append() add complete elements, not just start/end tags.

wrapAll() should do it:

$('#facebook').children().wrapAll('<a href="http://facebook.com"></a>');

Upvotes: 1

levi
levi

Reputation: 22697

You can do it with this:

previous_dom =  $("#facebook").html();
$("#facebook").html('<a href="#" title="Facebook" class="facebook_c">' + previous_dom +'</a>')

Upvotes: 0

Related Questions