javascript - How to wrap every 4 elements in a <li> tag with jquery? - Stack Overflow

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

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?

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?

Share Improve this question edited Mar 10, 2015 at 11:52 tomrozb 26.3k31 gold badges106 silver badges126 bronze badges asked Mar 10, 2015 at 10:48 XeenXeen 7,01317 gold badges69 silver badges113 bronze badges 3
  • Why would the menu have that structure in the first place? – Paulie_D Commented Mar 10, 2015 at 10:52
  • 1 Have you tried anything? Which bit are you finding difficult? It's just: Get all product divs, loop them, add them to a <li> (which you add to the <ul>), and every 4 loops change to a new <li> – musefan Commented Mar 10, 2015 at 10:52
  • Need to fix source. You have invalid markup. <div> is not a valid child of <ul> therefore you can't rely on all browsers to render them inside the <ul> – charlietfl Commented Mar 10, 2015 at 10:54
Add a ment  | 

1 Answer 1

Reset to default 7

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744875840a4598541.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信