I am trying to wrap a certain number of elements in a div
. The problem is that the number of elements can vary based on the user's input. So the number of elements could be 2, 3, 4, or even more. I have a variable that tells me how many elements should be wrapped. So, for instance, my page may have this:
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
Now I need to wrap those in another div
based on my variable. So, if my variable held a value of 3, it would look like this:
<div class="testing">
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
</div>
<div class="testing">
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
</div>
I was using this code:
$(this).add($(this).next())
.add($(this).next().next())
.wrapAll('<div class="testing"></div>');
The problem with that is that I would need to know how many elements are going to be there. Is there a dynamic way to do this? I also saw the slice
function and tried to use it like this:
for(var i=0;i<img_cnt;i+=img_row){
obj.children().slice(i,i+img_row).wrapAll('<div class="row"></div>');
}
It is not working, though. I have 8 div
s. It should be wrapping 3 together, so I should have 3 new div
s with 3 in the first 2 and 2 in the last, since there are only 8 div
s. However, I get 3 div
s in the first new div
, then the next 2 div
s are not wrapped at all, and then the last 3 div
s are wrapped in a new div
. I am not sure why it is not wrapping it right. Do you have any ideas on how to do this or maybe even a better method?