Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Skip every 4 and wrap every 3 child

I have parent with divs like this:

<div class="products">
    <div class="product"></div>
    <div class="product"></div>
    <div class="product"></div>
    <div class="product"></div>
    <div class="product"></div>
    <div class="product"></div>
    <div class="product"></div>
    <div class="product"></div>
</div>

I need to wrap every 3 elements and skip every 4, like this:

<div class="products">
    <div class="wrap">
        <div class="product"></div>
        <div class="product"></div>
        <div class="product"></div>
    </div>
    <div class="product"></div>
    <div class="wrap">
        <div class="product"></div>
        <div class="product"></div>
        <div class="product"></div>
    </div>
    <div class="product"></div>
</div>

I’m trying doing like this, but it’s only wrap each 3 elements

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var divs = $(".products .product");
for (var i = 0; i < divs.length; i +=3) { divs.slice(i, i + 3).wrapAll("<div class='wrap'>
    </div>");
}

>Solution :

You need to add the correct end in the slice. Also once wrapped
you need to update i with correct value

var divs = $(".products .product");
let i = 0;

while (i < divs.length) {
  divs.slice(i, i + 3).wrapAll("<div class='wrap'> </div>");
  i = i + 4

}
.wrap {
  border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="products">
  <div class="product">1</div>
  <div class="product">2</div>
  <div class="product">3</div>
  <div class="product">4</div>
  <div class="product">5</div>
  <div class="product">6</div>
  <div class="product">7</div>
  <div class="product">8</div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading