jQuery – use wrap() to wrap multiple elements?

You can use the .wrapAll() method.

$('form > input').each(function(){
    $(this).next('label').andSelf().wrapAll('<div class="test"/>');
});

If your markup has always the exact same order, I’d prefer to use:

var $set = $('form').children();    
for(var i=0, len = $set.length; i < len; i+=2){
    $set.slice(i, i+2).wrapAll('<div class="test"/>');
}    

Should be significant faster.

Ref.: .wrapAll(), .andSelf(), .slice()

Leave a Comment