views:

60

answers:

2

Hi,

I am a little stumped with how to do this.

I am using jQuery and wish to encapsulate certain sets of divs with a div.

For example I have:

<div id="groups">  
    <div class="group-1">x</div>
    <div class="group-1">x</div>
    <div class="group-2">x</div>
    <div class="group-2">x</div>
    <div class="group-3">x</div>
</div>

And wish to end up with:

<div id="groups">  
  <div id="set-1">
    <div class="group-1">x</div>
    <div class="group-1">x</div>
  </div>
  <div id="set-2">
    <div class="group-2">x</div>
    <div class="group-2">x</div>
  </div>
  <div id="set-3">
    <div class="group-3">x</div>
  </div>
</div>

I am able to cycle through each div and add a div around each one but not the way I want above. Any advice appreciate.

Thanks.

+4  A: 

See .wrapAll()

$(".group-1").wrapAll('<div id="set-1" />');
$(".group-2").wrapAll('<div id="set-2" />');
$(".group-3").wrapAll('<div id="set-3" />');

If you need the selector to match classes inside the #groups div only, use the child selector, e.g. $('#groups > .group-1')

Andy E
Thanks, exactly what I needed!
lafoaug
+2  A: 

If you need a more generic solution, e.g. you don't know the number of groups (more often the case in my experience) you can do something like this:

var groups = {};
$("#groups div").each(function(i) {
    var c = $(this).attr("class");
    if(!groups[c]) groups[c] = [];
    groups[c].push(this);
});
for(var i in groups) {
    $(groups[i]).wrapAll("<div id='" + i.replace('group', 'set') +"' />");
}

You can view a demo here, this will work with any number of group-X that may be inside #groups, making a bit more flexible. If you're able to change your markup you can make this simpler, but I'm guessing if that was an option you wouldn't be asking this question in the first place :)

Nick Craver
+1 for genericness, I thought about adding a similar solution to my answer but decided to wait and see if it was necessary. You might need a `hasOwnProperty` check in that `for...in`, or you could just use `$.each()` on the object.
Andy E