Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encapsulate a set of divs with another div in jQuery

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.

like image 436
lafoaug Avatar asked Jun 10 '10 10:06

lafoaug


People also ask

How do you copy the content of a div into another div using jQuery?

First, select the div element which need to be copy into another div element. Select the target element where div element is copied. Use the append() method to copy the element as its child.

Can a div contain another div?

Example: This example describes how we can place a div inside another div. As we can see the inner div container occupied the leftward portion of the inner space. To move the inner div container to the centre of the parent div we have to use the margin property of style attribute.

How do I append a div under another div?

Div itself is a block element that means if you add div then it would start from under the another div. Still you can do this by using the css property that is display:block; or assign width:100%; add this to the div which you want under another div.

Can you wrap a div in an a tag?

Using this as a example. Yes, putting an anchor around a block is valid in HTML5 specs. Try cutting and pasting the script into the free online validator or pasting the link to your web page.


1 Answers

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

like image 50
Andy E Avatar answered Nov 07 '22 23:11

Andy E