Alexis Alexis - 8 days ago 6
jQuery Question

Surround an element using jQuery

I wish surround an

<a>
with
<h1></h1>
. I'm trying :

<a class="toto">TEST</a>


var test = $('.toto');
test.before('<h2>');
test.after('</h2>');


However it does not work. How can I do this?

Answer

Your current code doesn't work as you can only append whole elements to the DOM. The output of what you're trying would be this:

<h2></h2>
<a class="toto">TEST</a>
<h2></h2>

To do what you require, use wrap():

$('.toto').wrap('<h2 />'); // or .wrap('<h1 />');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="toto">TEST</a>