Rafee
Rafee

Reputation: 4078

Wrapping or grouping of elements with jQuery

I have paragraphs and these are not arranged or grouped. Now, I want to group with a class grouped

HTML

<p>Para 1</p>
<p>Para 2</p>
<div class="line"></div>
<p>Para 3</p>
<p>Para 4</p>
<p>Para 5</p>

Desired Result

<div class="grouped">
    <p>Para 1</p>
    <p>Para 2</p>
</div>

<div class="line"></div>

<div class="grouped">
    <p>Para 3</p>
    <p>Para 4</p>
    <p>Para 5</p>
</div>

I know wrapAll is function can help this but, it grouped all p in same and one element grouped and I need it in different grouped elements

JSFiddle

JSFiddle

Note

p may be more than listed above in each segment

Upvotes: 0

Views: 208

Answers (4)

Ram
Ram

Reputation: 144699

You can also use a simple while loop:

var $p = $('p').parent();

while($p.children('p').length) {
      $p.children('p:first')
        .nextUntil('.line')
        .addBack()
        .wrapAll('<div class="grouped"/>');
}

http://jsfiddle.net/LGhND/

Upvotes: 0

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

This will handle multiple .line between p tags

var last = $(".line").length;
var divGroup = '<div class="grouped"/>';
$(".line").each(function(i,e){
    var segment1 = $(this).prevAll("p:not(.grouped)");
    $(segment1.get().reverse()).wrapAll(divGroup);
    if( i == last-1){
        $(this).nextAll("p:not(.grouped)").wrapAll(divGroup);
    }
});

JS Fiddle http://jsfiddle.net/6a87E/5/

Upvotes: 0

lavrik
lavrik

Reputation: 1474

Try this demo this demo. Iterate over $("p") and group them.

$("p").each(function(ix,el){
   if($(el).next().is('.line')) - go to next group
   else add to current

Upvotes: 2

adeneo
adeneo

Reputation: 318302

Iterate, and check if the element is already wrapped, if not use nextUntil to get the collection of paragraphs and wrap them

$('p').each(function() {
    if ( ! $(this).closest('.grouped').length) 
        $(this).nextUntil('div').addBack().wrapAll("<div class='grouped' />");
});

FIDDLE

Upvotes: 1

Related Questions