andresgl
andresgl

Reputation: 117

Wrap deferents html tags with a div using jQuery

I have the following lines in HTML:

<header class="title">
    <h3>Billing Address</h3>
</header>

<address>
 <p>Address</p>
</address>

And I would like to wrap them between a new div using jQuery because I don't have access to the HTML.

If I use .before() and .after(), it doesn't work

$('header').before('<div="new-div">');
$('address').after('</div>');

I have tried with .wrap() and .append(), but also doesn't work.

The result shoulbe be:

<div class="new-div">
    <header class="title">
        <h3>Billing Address</h3>
    </header>

    <address>
     <p> Address </p>
    </address>
</div>

Thank you!

Upvotes: 4

Views: 44

Answers (2)

Hardik Pithva
Hardik Pithva

Reputation: 1745

You can also use prepend() along with append()

$('header').prepend('<div="new-div">');
$('address').append('MYDIV</div>');

Check this fiddle

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82241

Use .wrapAll() instead of .wrap():

wrapAll : Wrap an HTML structure around all elements in the set of matched elements.

$( "header,address" ).wrapAll( "<div class='new' />");

Working Demo

Upvotes: 6

Related Questions