Probocop
Probocop

Reputation: 10552

jQuery - use wrap() to wrap multiple elements?

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!

Upvotes: 44

Views: 62059

Answers (4)

Lida
Lida

Reputation: 137

If you have something like this:

<input id="input1">
<label id="label1">
<input id="input2">
<label id="label2">

Then you can use jQuery:

 jQuery("#input1").next().andSelf().wrapAll('<div id="newDiv" />');
 jQuery("#input2").next().andSelf().wrapAll('<div id="newDiv" />');

and get this:

<div id="newDiv">
  <input id="input1">
  <label id="label1">
</div>
<div id="newDiv">
  <input id="input2">
  <label id="label2">
</div>

Worked for me :-)

Upvotes: 1

jAndy
jAndy

Reputation: 235962

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

Upvotes: 113

James
James

Reputation: 111870

$('input+label').each(function(){
    $(this).prev().andSelf().wrapAll('<div>');
});​

Upvotes: 5

RaYell
RaYell

Reputation: 70404

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>

Upvotes: 0

Related Questions