tags:

views:

297

answers:

1

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 divs. It should be wrapping 3 together, so I should have 3 new divs with 3 in the first 2 and 2 in the last, since there are only 8 divs. However, I get 3 divs in the first new div, then the next 2 divs are not wrapped at all, and then the last 3 divs 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?

+3  A: 

Your code isn't working because children is changing. Try using slice on a constant set:

var all = $('.test'); 
for(i=0; i < all.length; i += img_row) {
   all.slice(i, i + img_row).wrapAll('<div class="row" />'); 
}

Example: http://jsbin.com/upaji

Kobi
Thanks that seems to work but for some reason it is skipping the first element. Any ideas?
ngreenwood6
Make sure you use `i=0`, and that you haven't forgot a `.next()` somewhere there. It should work well, can you please post a minimal example where this isn't working? (Try http://jsbin.com/ )
Kobi
its weird it works in ie but not in firefox. also noticed that the last image is not wrapped. I am assuming that its probably because the first one isnt being wrapped.
ngreenwood6
@ngreenwood6 - I've just tested it on Firefox, IE and Chrome, and it seems to work well. I'm going to need more details to help you... Do you have other JavaScript running there? Maybe different classes for the first/last items?
Kobi