Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap elements inside a div using jQuery

I have this:

<div>content element</div> <div class="accordionTrigger">   <div><h1>title</h1></div>   <p>text</p>   <p>text</p>   <p>text</p>   ... </div> <div>content element</div> <div>content element</div> 

I need to wrap all the p-tags inside a div like this:

    <div>content element</div>     <div class="accordionTrigger">       <div><h1>title</h1></div>       <div class="moreInfo">             <p>text</p>         <p>text</p>         <p>text</p>         ...       </div>     </div>     <div>content element</div>     <div>content element</div> 

can it be done with jQuery?


If I have more than one <div class="accordionTrigger"></div>, like this:

<div>content element</div> <div class="accordionTrigger">   <div><h1>title</h1></div>   <p>text</p>   <p>text</p>   ... </div> <div>content element</div> <div class="accordionTrigger">   <div><h1>title</h1></div>   <p>text</p>   <p>text</p>   ... </div> 

the result will be:

<div>content element</div> <div class="accordionTrigger">   <div><h1>title</h1></div>   <p>text</p>   <p>text</p>   <p>text</p>   <p>text</p>   ... </div> <div>content element</div> <div class="accordionTrigger">   <div><h1>title</h1></div> </div> 

can I avoid that?

like image 286
stig Avatar asked Feb 15 '12 10:02

stig


People also ask

What does the jQuery wrap () function do?

jQuery wrap() method is used to wrap specified HTML elements around each selected element. The wrap () function can accept any string or object that could be passed through the $() factory function. Syntax: $(selector).

Which of the following functions wrap a single element in a div element that has a border?

The wrap() method wraps specified HTML element(s) around each selected element.

How do you wrap two divs?

use Jquery . wrapAll() - It wraps the html structure around all the matched elements.

Can you wrap a div in an a tag?

In general, you can't have an inline element, like an anchor (<a>) or span, wrap around a block level element like a division (<div>) or heading.


1 Answers

Check the .wrapAll() method:

$('.accordionTrigger p').wrapAll('<div class="moreInfo"></div>'); 

The wrapAll() method will wrap all the elements matched into another element (compared to the .wrap() method which wraps the matched elements individually)

DEMO

like image 141
Didier Ghys Avatar answered Sep 22 '22 01:09

Didier Ghys