How to wrap every 4 elements in a <li> tag with jquery?

无人久伴 提交于 2020-01-17 08:54:10

问题


I need to wrap every 4 .product divs in a row within a <li> tag so that when there's:

<ul>
  <div class="product">...</div>
  <div class="product">...</div>
  <div class="product">...</div>
  <div class="product">...</div>
  <div class="product">...</div>
  <div class="product">...</div>
</ul>

it gets turned in to a:

<ul>
  <li>
    <div class="product">...</div>
    <div class="product">...</div>
    <div class="product">...</div>
    <div class="product">...</div>
  </li>
  <li>
    <div class="product">...</div>
    <div class="product">...</div>
  </li>
</ul>

In the example I've given 6 products because it must close the wrapping if those are the last elements anyway.

Can you please show me how this can be done with jquery?


回答1:


You can use for loop along to iterate over every 4th element and then wrap the 3 previous elements along with current 4n element using .wrapAll():

var productdivs = $("ul .product");
for(var i = 0; i < productdivs.length; i+=4) {
  productdivs.slice(i, i+4).wrapAll("<li></li>");
}

Working Demo



来源:https://stackoverflow.com/questions/28961721/how-to-wrap-every-4-elements-in-a-li-tag-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!