Wrap every 3 divs in a div

前端 未结 6 1973
执念已碎
执念已碎 2020-11-22 09:03

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...



        
6条回答
  •  北恋
    北恋 (楼主)
    2020-11-22 10:02

    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("
    "); }

    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.

提交回复
热议问题