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.
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.
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.
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.
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With