user2413333
user2413333

Reputation: 1405

Wrap pairs of elements?

If you have the following code:

<div class="parent">

    <div class="1a"></div>
    <div class="1b"></div>

    <div class="2a"></div>
    <div class="2b"></div>

    <div class="3a"></div>
    <div class="3b"></div>


</div>

Is there an efficient/easy way to wrap a new div around each a + b so it finishes looking like this:

<div class="parent">

   <div class="new-1">        
       <div class="1a"></div>
       <div class="1b"></div>
   </div>

   <div class="new-2">        
       <div class="2a"></div>
       <div class="2b"></div>
   </div>

   <div class="new-3">        
       <div class="3a"></div>
       <div class="3b"></div>
   </div>


</div>

For example can I say something like:

wrap every two divs inside .parent with <div class="new-(incremental variable)"></div> (the new wrapping divs need to have a unique class)

Upvotes: 1

Views: 139

Answers (3)

PSL
PSL

Reputation: 123739

Like this?

$('.parent > div:odd').each(function(i){
    $(this)
       .prev()
       .addBack()
       .wrapAll($('<div/>',{'class': 'new-' + (i+1)}));
});

Demo

Get the odd ones selected i.e 1, 3, 5 etc based on index(0 based); Iterate the odd ones get the prev element relative to the odd(which needs to be paired), use andSelf addBack to select that too and then use wrapAll on the pair.

if you want to ignore first x of them then do this:

$('.parent > div:gt(' + (x-1) + '):odd').each(function(i){
    $(this)
         .prev()
         .addBack()
         .wrapAll($('<div/>',{'class': 'new-' + (i+1)}));
})

Demo

Upvotes: 7

user2540562
user2540562

Reputation: 1

I'm not sure what you wish to achieve with the new wrapper divs but nth-child in CSS might be useful. Try something like this:

div.parent div {width:50%;}
div.parent div:nth-child(odd) {clear:both; float:left;}
div.parent div:nth-child(even) {float:right;}

...which will give you pairs of divs side by side.

Upvotes: 0

Aart Stuurman
Aart Stuurman

Reputation: 3608

You can literally use jQueries Wrap function. Take a look here!

http://api.jquery.com/wrap/

Upvotes: 0

Related Questions