Reputation: 1586
I've these divs
<div class="col_1_6"></div>
<div class="col_1_4"></div>
<div class="col_1_6"></div>
<div class="col_1_4"></div>
<div class="col_1_4"></div>
<div class="col_1_6"></div>
I want whatever the order of the divs, wrap col_1_4 and col_1_6 in a div called row_content
<div class="row_content">
<div class="col_1_6"></div>
<div class="col_1_4"></div>
</div>
<div class="row_content">
<div class="col_1_4"></div>
<div class="col_1_6"></div>
</div>
I already try this :
$('.col_1_6, .col_1_4').wrapAll('<div class="row"></div>')
But it wrap all the divs not each two divs.
Thanks for the help.
Upvotes: 0
Views: 325
Reputation: 302
I've found this method which works
$(".col_1_6").each(function(index) {
$(this).next(".col_1_4").andSelf().wrapAll("<div class='row' />")
});
but this only work if all div are in this order .col_1_6 > .col_1_4 and not .col_1_4 > col_1_6 as in your html
http://jsfiddle.net/mrjx9dav/11/
Upvotes: 1
Reputation: 8181
Another not-so-pretty solution that wraps every 2 divs that has the class starting with col_1
.
$('div[class^="col_1"]').each(function(ind) {
ind%2 === 0 && ($(this).add($(this).next()).wrapAll('<div class="row"></div>'));
});
Upvotes: 0
Reputation: 33880
You can select all your divs
and then do a for
loop that increment by 2 every iteration.
With the index of the loop, you can then use .slice
on the jQuery element and that wrap your divs
.
var $divs = $('.col_1_6, .col_1_4');
for(var i = 0; i < $divs.length; i+=2){
$divs.slice(i, i+2).wrapAll('<div class="row"></div>');
console.log($divs);
}
.row{
background: red;
margin : 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="col_1_6">1</div>
<div class="col_1_4">2</div>
<div class="col_1_6">3</div>
<div class="col_1_4">4</div>
<div class="col_1_4">5</div>
<div class="col_1_6">6</div>
Upvotes: 3