开发者

How to split content with jquery after certain amount of divs

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">
        bl开发者_运维问答ablaform 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜