Tony Tony - 6 months ago 7
jQuery Question

Wrapping multiple child elements in place

I have some HTML which is essentially the same as the following:

<div id="row-1" class="row">
<div class="col1"></div>
<div class="col2"></div>
<div class="col3"></div>
<div class="col4"></div>
<div class="col5"></div>
</div>
<div id="row-2" class="row">
<div class="col1"></div>
<div class="col2"></div>
<div class="col3"></div>
<div class="col4"></div>
<div class="col5"></div>
</div>
<div id="row-3" class="row">
<div class="col1"></div>
<div class="col2"></div>
<div class="col3"></div>
<div class="col4"></div>
<div class="col5"></div>
</div>


Now, I need to use jQuery to select col2, col3, col4 and wrap a new div pair around them to generate html like this:

<div id="row-n" class="row">
<div class="col1"></div>
<div class ="wrapped-1">
<div class="wrapped-2">
<div class="col2"></div>
<div class="col3"></div>
<div class="col4"></div>
</div>
</div>
<div class="col5"></div>
</div>


I'm having some difficulty. I have tried using this:

$('div[id^="row-"]')
.children('.col2, .col3, .col4')
.wrapInner('<div class="wrapped-2" />')
.wrapInner('<div class="wrapped-1" />');


... which gives the closest result to that which I want, however I need the tags outside as opposed to inserted into the selected elements.
.wrapAll() appears to just group all of the items into the first row and strip them from the subsequent rows which is just plain wrong.

I am relatively new to jQuery so any help and/or advice on this will be greatly appreciated!

Answer

Actually the method that should be used in this case is wrapAll method, it wraps all the selected elements with the specified element(s), by using each method you can prevent this, so only children of a specific element are wrapped.

$('div[id^="row-"]').each(function() {
    $(this).children('.col2, .col3, .col4')
           .wrapAll('<div class="wrapped-1"><div class="wrapped-2"></div></div>');
});

http://jsfiddle.net/rVfp9/