rama
rama

Reputation: 21

How to add div with class every second item

Please help.. How to add div with class every second item. I have a list item:

<div class="col-sm-3">
    <div class="product rotation">
        <div>data 1</div>
    </div>

    <div class="product rotation">
        <div>data 2</div>
    </div>

    <div class="product rotation">
        <div>data 3</div>
    </div>

    <div class="product rotation">
        <div>data 4</div>
    </div>
</div>

I want to add div with class every second item:

<div class="col-sm-12">
    <div class="col-sm-3 col-md-3 double-product">
        <div class="product rotation">
            <div>data 1</div>
        </div>

        <div class="product rotation">
            <div>data 2</div>
        </div>
    </div>
</div>

<div class="col-sm-12">
    <div class="col-sm-3 col-md-3 double-product">
        <div class="product rotation">
            <div>data 3</div>
        </div>

        <div class="product rotation">
            <div>data 4</div>
        </div>
    </div>
</div>

How to add div with class every second item. Thank you.

Upvotes: 0

Views: 140

Answers (1)

rrk
rrk

Reputation: 15846

In order to achieve the output provided in your code, use the following.
This uses wrapAll() in a loop.

products = $('.product');

for(var i = 0; i < products.length; i+=2) {
  products.slice(i, i+2).wrapAll('<div class="col-sm-12"><div class="col-sm-3 col-md-3 double-product"></div></div>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="col-sm-3">
    <div class="product rotation">
        <div>data 1</div>
    </div>

    <div class="product rotation">
        <div>data 2</div>
    </div>

    <div class="product rotation">
        <div>data 3</div>
    </div>

    <div class="product rotation">
        <div>data 4</div>
    </div>
</div>

Upvotes: 1

Related Questions