Reputation: 1405
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
Reputation: 123739
Like this?
$('.parent > div:odd').each(function(i){
$(this)
.prev()
.addBack()
.wrapAll($('<div/>',{'class': 'new-' + (i+1)}));
});
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)}));
})
Upvotes: 7
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
Reputation: 3608
You can literally use jQueries Wrap function. Take a look here!
Upvotes: 0