Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 842
andresgl Avatar asked Mar 13 '23 11:03

andresgl


2 Answers

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

like image 65
Milind Anantwar Avatar answered Mar 16 '23 00:03

Milind Anantwar


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

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

Check this fiddle

like image 45
Hardik Pithva Avatar answered Mar 16 '23 00:03

Hardik Pithva