tags:

views:

43

answers:

3

How would I go about using wrap() to wrap multiple elements (with different classes) inside a <div>?

For example, on the form I'm working on there is a big list of checkbox inputs and labels in the form of:

<input>
<label>
<input>
<label>

etc

I'm wanting to wrap a <div> around the input and label, so the result would be:

<div>
  <input>
  <label>
</div>
<div>
  <input>
  <label>
</div>

Thanks!

A: 

jQuery function wrapAll allows you to wrap multiple elements but if you have a DOM like you wrote then it won't work too well as you can't easily match a part of label and input with a selector. I suggest adding some classes to each part and then using wrapAll.

<input class="i1"/>
<label class="i1"/>
<input class="i2"/>
<label class="i2"/>

$('.i1').wrapAll('<div/>');
$('.i2').wrapAll('<div/>');

This will give you

<div>
    <input class="i1"/>
    <label class="i1"/>
</div>
<div>
    <input class="i2"/>
    <label class="i2"/>
<div>
RaYell
+4  A: 

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()

jAndy
This is probably the best way of doing that.
RaYell
Perfect, just what I was after, thank you very much.
Probocop
A: 
$('input+label').each(function(){
    $(this).prev().andSelf().wrapAll('<div>');
});​
J-P