My code wraps a div around every 5 child divs. But the wrapping should only take place in the div "partnerwrap", can someone help me?
var divs = $(".partnerwrap > .partner_item");
for (var i = 0; i < divs.length; i += 5) {
divs.slice(i, i + 5).wrapAll("<div class='group'></div>");
}
.partner_item {
width: 50px;
height: 50px;
margin: 10px;
float: left;
background-color: #999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content1">
<div class="partnerwrap">
<div class="partner_item even">1</div>
<div class="partner_item odd">2</div>
<div class="partner_item even">3</div>
<div class="partner_item odd">4</div>
<div class="partner_item even">5</div>
<div class="partner_item odd">6</div>
<div class="partner_item even">7</div>
<div class="partner_item odd">8</div>
</div>
</div>
<div class="content2">
<div class="partnerwrap">
<div class="partner_item even">9</div>
<div class="partner_item odd">10</div>
</div>
</div>
If you use Ids to identify the content divs, and use class to group them, you can do something like this:
$(".content").each(function() {
var divs = $(".partnerwrap > .partner_item", this);
for (var i = 0; i < divs.length; i += 5) {
divs.slice(i, i + 5).wrapAll("<div class='group'></div>");
}
});
.partner_item {
width: 50px;
height: 50px;
margin: 10px;
float: left;
background-color: #999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content1">
<div class="partnerwrap">
<div class="partner_item even">1</div>
<div class="partner_item odd">2</div>
<div class="partner_item even">3</div>
<div class="partner_item odd">4</div>
<div class="partner_item even">5</div>
<div class="partner_item odd">6</div>
<div class="partner_item even">7</div>
<div class="partner_item odd">8</div>
</div>
</div>
<div class="content2">
<div class="partnerwrap">
<div class="partner_item even">9</div>
<div class="partner_item odd">10</div>
</div>
</div>
Check it in fiddle