Rohan
Rohan

Reputation: 1657

jQuery nth child trouble

I'm trying to wrap every set of three .item divs in a larger div, how can I do that?

Original:

<div class="item">..</div>
<div class="item">..</div>
<div class="item">..</div>
<div class="item">..</div>
<div class="item">..</div>
<div class="item">..</div>

After jQuery:

<div class="row">
    <div class="item">..</div>
    <div class="item">..</div>
    <div class="item">..</div>
</div>
<div class="row">
    <div class="item">..</div>
    <div class="item">..</div>
    <div class="item">..</div>
</div>

I'm having trouble figuring out the nth child equation - any help?

Upvotes: 0

Views: 78

Answers (1)

Nick Craver
Nick Craver

Reputation: 630637

You can do it using .slice() and .wrapAll() like this:

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

You can test it here

Upvotes: 1

Related Questions