How to wrap div around multiple of the same class elements

You can loop pretty quickly through your <div> elements using a for loop. In the below code, just change the initial selector here to grab all those siblings divs, e.g. #content > div.entry or wherever they are:

var divs = $("div.entry");
for(var i=0; i<divs.length;) {
  i += divs.eq(i).nextUntil(':not(.entry)').andSelf().wrapAll('<div />').length;
}​

You can give it a try here. We're just looping through, the .entry <div> elements using .nextUntil() to get all the .entry elements until there is a non-.entry one using the :not() selector. Then we're taking those next elements, plus the one we started with (.andSelf()) and doing a .wrapAll() on that group. After they're wrapped, we're skipping ahead either that many elements in the loop.


I just whipped up a simple custom solution.

var i, wrap, wrap_number = 0;
$('div').each(function(){ //group entries into blocks "entry_wrap_#"
    var div = $(this);
    if (div.is('.entry')) {
        wrap = 'entry_wrap_' + wrap_number;
        div.addClass(wrap);
    } else {
        wrap_number++;
    }
});
for (i = 0; i <= wrap_number; i++) { //wrap all blocks and remove class
    wrap = 'entry_wrap_' + i;
    $('.' + wrap).wrapAll('<div class="wrap"/>').removeClass(wrap);
}