views:

24

answers:

1

I have a form like this:

<div class="content">
  <form>
    <div class="item">
      blablaform stuf
    </div>
    <div class="item">
      blablaform stuf
    </div>
    <div class="item">
      blablaform stuf
    </div>
    <div class="item">
      blablaform stuf
    </div>
  </form>
</div>

Now I want to wrap a few of the item divs inside form. Basically like this:

<div class="content">
  <form>
    <div class="wrapper">
      <div class="item">
        blablaform stuf
      </div>
      <div class="item">
        blablaform stuf
      </div>
    </div>
    <div class="wrapper">
      <div class="item">
        blablaform stuf
      </div>
      <div class="item">
        blablaform stuf
      </div>
    </div>
  </form>
</div>

How can I do it with jQuery? append()? :nth-child or how?

Thanks.

+3  A: 

Something like this would work:

var elems = $(".content div.item");
for(var i = 0; i < elems.length; i+=2) {
  elems.slice(i, i+2).wrapAll("<div class='wrapper'></div>");
}

You can test it out here, what this does is grab all the .item <div> elements in there, and every pair of 2 wraps them, if there are any left over (a last single one) it'll be wrapped by itself.


Or, let's make it reusable, as a plugin:

jQuery.fn.wrapSet = function (interval, wrapElem) {
  for(var i = 0; i < this.length; i+=interval) {
    this.slice(i, i+interval).wrapAll(wrapElem);
  }
  return this;
};

Then you can call it like this:

$(".content div.item").wrapSet(2, "<div class='wrapper'></div>");​

You can give that version a try here.

Nick Craver
I'm curious, just how awesome were you *before* JavaScript? =)
David Thomas
@David - I spend most of my day in C#/Oracle actually, JavaScript is just a hobby :)
Nick Craver