user2061791 February 2016

Using jQuery to group varying number of divs wtih same class until "last" class

I've seen other related questions but not quite like mine.

I have blocks of code with varying number of rows and want to group those rows, including the "last" div:

<div class="row"></div>
<div class="row"></div>
<div class="last"></div>
<br>
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
<div class="last"></div>
<br>
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
<div class="last"></div>

I want:

<div class="wrapper">
<div class="row"></div>
<div class="row"></div>
<div class="last"></div>
</div>
<br>
<div class="wrapper">
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
<div class="last"></div>
</div>
<br>
<div class="wrapper">
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
<div class="last"></div>
</div>

I've tried various find, addBefore, wrapAll variations but just can't get it.

I've tried variations of:

$(this).find(".row, .last").wrapAll('<div class="wrapper"></div>');

Answers


BenG February 2016

Here is one way:-

//find all the 'first' .row by checking the previous is not a .row
$('.row').prev(':not(.row)').next().each(function() {
  //wrap all next elements until you find something not a div
  $(this).nextUntil(':not(div)').addBack().wrapAll($("<div></div>", {
    class: 'wrapper'
  }));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="row"></div>
<div class="row"></div>
<div class="last"></div>
<br>
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
<div class="last"></div>
<br>
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
<div class="last"></div>


Thangaraja February 2016

We can acheive this by combining prevAll and wrapAll. Below is the ocde

$("div.last").each(function() {
  $(this).prevAll(".row").addBack().wrapAll("<div class='wrapper' />"); 
});

Demo : https://jsfiddle.net/wx8074qn/3/

Post Status

Asked in February 2016
Viewed 2,449 times
Voted 6
Answered 2 times

Search




Leave an answer