Is it possible to use nth-child selectors to wrap 3 divs using .wrapAll? I can't seem to work out the correct equation.

so...

<div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
</div>

becomes...

<div>
   <div class="new">
        <div></div>
        <div></div>
        <div></div>
   </div>
   <div class="new">
        <div></div>
        <div></div>
        <div></div>
   </div>
</div>

推荐答案

You can do it with .slice(), like this:

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

You can try out a demo here, all we're doing here is getting the elements you want to wrap and looping through them, doing a .wrapAll() in batches of 3 then moving to the next 3, etc. It will wrap 3 at a time and however many are left at the end, e.g. 3, 3, 3, 2 if that's the case.

Jquery相关问答推荐

如果在视窗中有相同的数据属性值,则jQuery/添加类

如何使 Bootstrap 轮播滑块使用移动左/右滑动

jQuery中的多个 Select 器链接?

标识符 (id) 是否有通配符 Select 器?

jQuery中的正则表达式字段验证

错误找不到 jquery-2.0.2.min.map

如何通过 Select 插件使用 jQuery 验证?

javascript中的描述关键字

按百分比zoom div的内容?

如何知道字体(@font-face)是否已经加载?

使用 JQuery / JavaScript 调用/单击 mailto 链接

在 JQuery .trigger 上传递参数

在不丢失光标位置的情况下更新输入值

判断文本框是否有空值

CSS3 相当于 jQuery slideUp 和 slideDown?

将多个 JavaScript 文件合并为一个 JS 文件

使用 jQuery Select 空文本输入

添加到数组 jQuery

如何判断值是否为 JSON 对象?

textarea 的 val() 与 text()