0

We have a 10 divs as our html result:

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

How to put each started 4 divs group into new container by jQuery? I want to get result like this:

<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="container">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="container">
  <div></div>
  <div></div>
</div>

Remember that sometimes it will be 0 divs, sometimes 3, sometimes 8, sometimes 14. Thanks for your help.

PS: Yes, I tried wrap, but when i set 4 it is not working with 2 or 7 divs. I tried lot of ifs and sstrange solutions...

var goals = $('.goal-slider').find('.goal');
console.log(goals.length);
goals.each(function(index){
    if(index%4 != 0 && index == goals.length) {
        goals.slice(index - index%4, index).wrap('<div class="goal-slide"></div>');
    }
    if(index%4 == 0 && index != goals.length - 1) {
        goals.slice(index - 3, index).wrap('<div class="goal-slide"></div>');
    }
});
Artimal
  • 651
  • 7
  • 24
  • See http://stackoverflow.com/questions/3366529/wrap-every-3-divs-in-a-div – Nenad Vracar Mar 07 '17 at 16:37
  • Dont you try anything? Show us some code at least. – Roy Bogado Mar 07 '17 at 16:38
  • Hello, have you tried researching the Jquery API documentation page? Everything you need is there. at least try reading it a bit.. [API Page](http://api.jquery.com/) – IndieRok Mar 07 '17 at 16:38
  • I tried lotof things with length, modulo, wrap, slice, after, before but it always was working bad, so that's why I am asking about best solution for that problem. I edited my post to show you my last jQuery try. – Artimal Mar 07 '17 at 16:42
  • ok, sorry to have doubt you had tried anything, let me check what I can do to help – IndieRok Mar 07 '17 at 17:00
  • Possible duplicate of [Wrap every 3 divs in a div](http://stackoverflow.com/questions/3366529/wrap-every-3-divs-in-a-div) – albert Mar 07 '17 at 17:56

1 Answers1

2

You can For Loop over every fourth element and wrap them with Jquery's WrapAll method. It will work even if you have an odd or even numbers of DIVs.

[Working example] I added a border to the wrapping div to show what is included in each pass

Credit where credit is due: Stackoverflow post

$(function(){
  var goals = $('.goal-slider').find('.goal');
  for(var i = 0; i < goals.length; i+=4) {
     goals.slice(i, i+4).wrapAll("<div class='goal-slide'></div>");
   }
});
Community
  • 1
  • 1
IndieRok
  • 1,778
  • 1
  • 14
  • 21
  • Oh my god it's so easy and best solution. I think my brain was just too tired after 10 hours of programming. Thank you IndieRok :) – Artimal Mar 07 '17 at 17:10
  • haha i know the feeling, no problem. don't push yourself too hard. cheers – IndieRok Mar 07 '17 at 17:13