简体   繁体   中英

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!

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

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

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

Check this fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM